| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImportWP\Common\Importer\File; |
| 4 |
|
| 5 |
use ImportWP\Common\Importer\Exception\FileException; |
| 6 |
|
| 7 |
abstract class AbstractFile |
| 8 |
{ |
| 9 |
|
| 10 |
/** |
| 11 |
* @var string $file_path |
| 12 |
*/ |
| 13 |
private $file_path; |
| 14 |
/** |
| 15 |
* @var resource $file_handle |
| 16 |
*/ |
| 17 |
private $file_handle; |
| 18 |
|
| 19 |
protected $current_record = false; |
| 20 |
|
| 21 |
private $current_file_position = -1; |
| 22 |
|
| 23 |
/** |
| 24 |
* File constructor. |
| 25 |
* |
| 26 |
* @param $file_path |
| 27 |
* @throws FileException |
| 28 |
*/ |
| 29 |
public function __construct($file_path) |
| 30 |
{ |
| 31 |
@ini_set('auto_detect_line_endings', TRUE); |
| 32 |
|
| 33 |
$this->file_path = $file_path; |
| 34 |
if (file_exists($this->file_path)) { |
| 35 |
$this->file_handle = fopen($this->file_path, 'r'); |
| 36 |
} else { |
| 37 |
throw new FileException(sprintf(__("File Not Found: %s", 'jc-importer'), $file_path)); |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
public function __destruct() |
| 42 |
{ |
| 43 |
if ($this->file_handle) { |
| 44 |
fclose($this->file_handle); |
| 45 |
} |
| 46 |
|
| 47 |
@ini_set('auto_detect_line_endings', FALSE); |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Get next record |
| 52 |
* |
| 53 |
* @return string |
| 54 |
*/ |
| 55 |
public function getNextRecord() |
| 56 |
{ |
| 57 |
$record = false === $this->current_record ? 0 : $this->current_record + 1; |
| 58 |
|
| 59 |
return $this->getRecord($record); |
| 60 |
} |
| 61 |
|
| 62 |
abstract public function getRecord($record); |
| 63 |
|
| 64 |
/** |
| 65 |
* Get previous Record |
| 66 |
* |
| 67 |
* @return array |
| 68 |
*/ |
| 69 |
public function getPreviousRecord() |
| 70 |
{ |
| 71 |
return $this->getRecord($this->current_record - 1); |
| 72 |
} |
| 73 |
|
| 74 |
public function saveFilePosition() |
| 75 |
{ |
| 76 |
$this->current_file_position = ftell($this->file_handle); |
| 77 |
} |
| 78 |
|
| 79 |
public function loadFilePosition($record = 0) |
| 80 |
{ |
| 81 |
|
| 82 |
if ($this->current_file_position >= 0) { |
| 83 |
fseek($this->file_handle, $this->current_file_position); |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
/** |
| 88 |
* @return resource |
| 89 |
* @throws FileException |
| 90 |
*/ |
| 91 |
public function getFileHandle() |
| 92 |
{ |
| 93 |
if (!in_array(get_resource_type($this->file_handle), array('stream', 'file'), true)) { |
| 94 |
throw new FileException(sprintf(__("File not found: %s", 'jc-importer'), $this->file_path)); |
| 95 |
} |
| 96 |
return $this->file_handle; |
| 97 |
} |
| 98 |
|
| 99 |
public function setCurrentRecord($index) |
| 100 |
{ |
| 101 |
$this->current_record = $index; |
| 102 |
} |
| 103 |
} |
| 104 |
|