Commit cd8b9f70e71a504b61f7ba46ab66f662730141e8

Authored by Mihail
1 parent 0c6fd004

add cleanUp method to Parser class

lib/CsvParser.php
... ... @@ -34,6 +34,8 @@ class CsvParser extends TableParser
34 34 {
35 35 parent::read();
36 36  
  37 + $this->cleanUp();
  38 +
37 39 return $this->result;
38 40 }
39 41  
... ... @@ -54,6 +56,10 @@ class CsvParser extends TableParser
54 56 $j = 0;
55 57 for ($i = 1; $i <= count( $this->row ); $i++) {
56 58  
  59 + if ( !isset( $this->row[ $i - 1 ] ) ) {
  60 + continue;
  61 + }
  62 +
57 63 if ( $this->isEmptyColumn( $this->row[$i - 1] ) ) {
58 64 $j++;
59 65 }
... ... @@ -70,4 +76,8 @@ class CsvParser extends TableParser
70 76 protected function isEmptyColumn( $val ){
71 77 return $val == '';
72 78 }
  79 +
  80 + protected function setResult( ){
  81 + $this->result[] = $this->row;
  82 + }
73 83 }
74 84 \ No newline at end of file
... ...
lib/Parser.php
... ... @@ -17,6 +17,9 @@ abstract class Parser
17 17 public $converter_conf = [];
18 18 protected $converter = NULL;
19 19  
  20 + /** @var экземляр SplFileObject читаемого файла */
  21 + public $file;
  22 +
20 23 /**
21 24 * @var array - результирующий массив с отпарсенными значениями
22 25 */
... ... @@ -28,9 +31,15 @@ abstract class Parser
28 31 /** @var bool
29 32 имеет ли файл заголовок который будет установлен ключами возвращемого массива*/
30 33 public $has_header_row = false;
  34 + /*
  35 + *если есть ключи, то колонки с пустыми значениями будут пропускаться (из ряда такие значения будут удаляться),
  36 + * например если в файле вторая колонка пустая то она будет удалена
  37 + * если есть $has_header_row - то первая значимая строка становится ключами, но пустые колонки не удаляются из ряда
  38 + * например если в файле вторая колонка пустая то ей будет назначен соответсвующий ключ (второй) из первой строки
  39 + * все описаное выше реализуется в дочернем семействе классов TableParser в методе filterRow()
  40 + * для xml происходит просто сопоставление переданных ключей с прочитанными
  41 + */
31 42  
32   - /** @var экземляр SplFileObject читаемого файла */
33   - public $file;
34 43  
35 44  
36 45  
... ... @@ -78,4 +87,14 @@ abstract class Parser
78 87 return $arr;
79 88  
80 89 }
  90 +
  91 + protected function cleanUp( )
  92 + {
  93 + unset( $this->file );
  94 + unset( $this->converter );
  95 + unset( $this->converter_conf );
  96 +
  97 + }
  98 +
  99 +
81 100 }
82 101 \ No newline at end of file
... ...
lib/ParserHandler.php
... ... @@ -60,24 +60,12 @@ class ParserHandler
60 60  
61 61 public function run()
62 62 {
63   - $result = [];
64   - if (count($this->custom_configuration)) {
  63 + $parser = $this->createObjectByConfiguration( $this->custom_configuration );
65 64  
66   - $parser = $this->createObjectByConfiguration($this->custom_configuration);
67   -
68   - try {
69   -
70   - $parser->setup();
71   - $result = $parser->read();
72   -
73   - } catch (\ErrorException $e) {
74   -
75   - echo $e->getMessage();
76   -
77   - }
78   -
79   - }
  65 + $parser->setup();
  66 + $result = $parser->read();
80 67  
  68 + unset($this->fileObject);
81 69 return $result;
82 70 }
83 71  
... ... @@ -106,6 +94,10 @@ class ParserHandler
106 94 {
107 95 return ObjectCreator::build($configuration);
108 96 }
  97 +
  98 +
  99 +
  100 +
109 101 }
110 102  
111 103  
... ...
lib/TableParser.php
... ... @@ -94,11 +94,8 @@ abstract class TableParser extends Parser {
94 94 // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД
95 95 $empty_lines = 0;
96 96  
97   -
98   -
99 97 }
100 98  
101   -
102 99 }
103 100 /**
104 101 * определяет первую значимую строку,
... ... @@ -131,7 +128,8 @@ abstract class TableParser extends Parser {
131 128 if ( $this->keys !== NULL ) {
132 129  
133 130 if (count($this->keys) !== count($this->row)) {
134   - throw new \Exception("Ошибка парсинга файла в строке # {$this->current_row_number}. Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными");
  131 + throw new \Exception("Ошибка парсинга файла в строке # {$this->current_row_number}.
  132 + Не соответсвие числа ключевых колонок (заголовка) - числу колонок с данными");
135 133 }
136 134  
137 135 $this->row = array_combine($this->keys, $this->row);
... ... @@ -161,15 +159,13 @@ abstract class TableParser extends Parser {
161 159 }
162 160  
163 161 protected function filterRow(){
164   - // если есть заголовок или ключи - все значения нужны, не фильтруем
165   - if ( $this->has_header_row || $this->keys !== NULL ) {
  162 + // если есть заголовок - все значения нужны, не фильтруем
  163 + if ( $this->has_header_row || $this->row === NULL ) {
166 164 return;
167 165 }
168   - // CustomVarDamp::dump( $this->row);
169 166 $this->row = array_filter( $this->row, function($val){
170 167 return !$this->isEmptyColumn($val);
171 168 });
172   - //CustomVarDamp::dump( $this->row);
173 169 }
174 170  
175 171 protected function isLastLine(){
... ...
lib/XlsxParser.php
... ... @@ -62,18 +62,13 @@ class XlsxParser extends TableParser {
62 62 $this->current_node = $xml->sheetData->row;
63 63 $this->current_node->rewind();
64 64 if ( $this->current_node->valid() ) {
65   -
66 65 parent::read();
67   -
68 66 }
69   -
70 67 }
71   -
72 68 }
73 69  
74   -
  70 + $this->cleanUp();
75 71 if ( $this->active_sheet ) {
76   -
77 72 // в настройках указан конкретный лист с которогшо будем производить чтение, поэтому и возвращаем подмассив
78 73 return $this->result[ $this->current_sheet ];
79 74 }else{
... ... @@ -90,7 +85,6 @@ class XlsxParser extends TableParser {
90 85 throw new \Exception( 'Ошибка создания временного каталога - ' . $this->path_for_extract_files );
91 86 }
92 87  
93   -
94 88 $zip = new \ZipArchive;
95 89 if ( $zip->open( $this->file->getPathname() ) === TRUE ) {
96 90 $zip->extractTo( $this->path_for_extract_files . '/' );
... ... @@ -226,9 +220,16 @@ class XlsxParser extends TableParser {
226 220 }
227 221 }
228 222  
229   - function __destruct()
  223 +
  224 + protected function cleanUp()
230 225 {
  226 + parent::cleanUp();
  227 + unset($this->strings_arr);
  228 + unset($this->sheets_arr);
  229 + unset($this->current_node);
  230 +
231 231 $this->deleteExtractFiles();
  232 +
232 233 }
233 234  
234 235  
... ...
lib/XmlParser.php
... ... @@ -24,16 +24,17 @@ class XmlParser extends Parser{
24 24  
25 25 }
26 26  
  27 + $this->cleanUp();
27 28 return $result;
28 29 }
29 30  
30 31  
31 32 /**
32 33 * Converts an XML string to a PHP array
33   - *
34   - * @uses recursiveXMLToArray()
35   - * @param string $file_path
36   - * @return array
  34 + * @param $file_path
  35 + * @return mixed
  36 + * @throws Exception
  37 + * @throws \Exception
37 38 */
38 39 protected function xmlToArray( $file_path ) {
39 40  
... ...
lib/YiiMultiparser.php
... ... @@ -17,6 +17,7 @@ class YiiMultiparser extends Component{
17 17  
18 18 public $configuration;
19 19 public $parserHandler;
  20 +public $filePath;
20 21  
21 22 public function init()
22 23 {
... ... @@ -29,6 +30,7 @@ public $parserHandler;
29 30  
30 31 public function parse( $filePath, $options = [] ){
31 32  
  33 + $this->filePath = $filePath;
32 34 $this->parserHandler->setup( $filePath, $options );
33 35  
34 36 return $this->parserHandler->run();
... ...