| 1 |
<?php |
| 2 |
/** |
| 3 |
* Data Importer Class |
| 4 |
* |
| 5 |
* @package Timetics |
| 6 |
*/ |
| 7 |
namespace Timetics\Base; |
| 8 |
|
| 9 |
defined( 'ABSPATH' ) || exit; |
| 10 |
|
| 11 |
use Exception; |
| 12 |
use Timetics\Utils\Validator; |
| 13 |
|
| 14 |
/** |
| 15 |
* Class Importer |
| 16 |
*/ |
| 17 |
abstract class Importer { |
| 18 |
use Validator; |
| 19 |
|
| 20 |
/** |
| 21 |
* Store file |
| 22 |
* |
| 23 |
* @var array |
| 24 |
*/ |
| 25 |
protected $file; |
| 26 |
|
| 27 |
/** |
| 28 |
* Store data that will be imported |
| 29 |
* |
| 30 |
* @var array |
| 31 |
*/ |
| 32 |
protected $data; |
| 33 |
|
| 34 |
/** |
| 35 |
* Store number of rows |
| 36 |
* |
| 37 |
* @var integer |
| 38 |
*/ |
| 39 |
protected $total_row = 0; |
| 40 |
|
| 41 |
/** |
| 42 |
* Store total imported rows |
| 43 |
* |
| 44 |
* @var integer |
| 45 |
*/ |
| 46 |
protected $total_imported_row; |
| 47 |
|
| 48 |
/** |
| 49 |
* Import data |
| 50 |
* |
| 51 |
* @return mixed |
| 52 |
*/ |
| 53 |
abstract function import(); |
| 54 |
|
| 55 |
/** |
| 56 |
* Read file that will be imported |
| 57 |
* |
| 58 |
* @param array $file |
| 59 |
* |
| 60 |
* @return void |
| 61 |
*/ |
| 62 |
public function read_file() { |
| 63 |
$file = $this->file; |
| 64 |
$file_type = ! empty( $file['type'] ) ? $file['type'] : ''; |
| 65 |
$file_name = ! empty( $file['tmp_name'] ) ? $file['tmp_name'] : ''; |
| 66 |
|
| 67 |
switch ( $file_type ) { |
| 68 |
case 'application/json': |
| 69 |
$this->data = JsonReader::get_data( $file_name ); |
| 70 |
break; |
| 71 |
case 'text/csv': |
| 72 |
$this->data = CsvReader::get_data( $file_name ); |
| 73 |
break; |
| 74 |
default: |
| 75 |
throw new Exception( esc_html__( 'You must provide a valid file type', 'timetics' ) ); |
| 76 |
} |
| 77 |
|
| 78 |
$this->set_total_row(); |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* Get total number of rows |
| 83 |
* |
| 84 |
* @return integer |
| 85 |
*/ |
| 86 |
public function get_total_rows() { |
| 87 |
return $this->total_row; |
| 88 |
} |
| 89 |
|
| 90 |
/** |
| 91 |
* Set total row |
| 92 |
* |
| 93 |
* @return void |
| 94 |
*/ |
| 95 |
protected function set_total_row() { |
| 96 |
if ( ! $this->data ) { |
| 97 |
return; |
| 98 |
} |
| 99 |
|
| 100 |
$this->total_row = count( $this->data ); |
| 101 |
} |
| 102 |
|
| 103 |
/** |
| 104 |
* Get total imported rows |
| 105 |
* |
| 106 |
* @return integer |
| 107 |
*/ |
| 108 |
public function get_total_imported_rows() { |
| 109 |
return $this->total_imported_row; |
| 110 |
} |
| 111 |
} |
| 112 |
|