| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\App\Services\Csv; |
| 4 |
|
| 5 |
use FluentSupport\App\Services\Includes\FileSystem; |
| 6 |
|
| 7 |
class CsvWriter |
| 8 |
{ |
| 9 |
protected $path; |
| 10 |
protected $fileName; |
| 11 |
protected $filePath; |
| 12 |
protected $delimiter = ','; |
| 13 |
protected $enclosure = '"'; |
| 14 |
protected $file; |
| 15 |
protected $fileMode = 'w+'; |
| 16 |
|
| 17 |
public function __construct() |
| 18 |
{ |
| 19 |
$this->fileName = uniqid().'.csv'; |
| 20 |
$this->path = $this->_getDir().'/_tempCSV'; |
| 21 |
$this->_mkdir(); |
| 22 |
$this->file = $this->_make_file(); |
| 23 |
} |
| 24 |
|
| 25 |
public function _getDir() |
| 26 |
{ |
| 27 |
$uploadDir = wp_upload_dir(); |
| 28 |
|
| 29 |
return $uploadDir['basedir'] .'/'. FLUENT_SUPPORT_UPLOAD_DIR; |
| 30 |
} |
| 31 |
|
| 32 |
public function _mkdir() |
| 33 |
{ |
| 34 |
if (!is_dir($this->path)) { |
| 35 |
mkdir($this->path, 0777, true); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
public function _make_file(){ |
| 40 |
$this->filePath = $this->path.'/'.$this->fileName; |
| 41 |
file_exists($this->filePath) ?? unlink($this->filePath); |
| 42 |
|
| 43 |
$f = fopen($this->filePath, $this->fileMode); |
| 44 |
|
| 45 |
if ($f === false) { |
| 46 |
die('Error opening the file ' . esc_html($this->filePath)); |
| 47 |
} |
| 48 |
|
| 49 |
return $f; |
| 50 |
} |
| 51 |
|
| 52 |
public function insertOne($row){ |
| 53 |
$this->file = fopen($this->filePath, 'a+'); |
| 54 |
fputcsv($this->file, $row, $this->delimiter, $this->enclosure); |
| 55 |
fclose($this->file); |
| 56 |
} |
| 57 |
|
| 58 |
public function insertAll($data){ |
| 59 |
$this->file = fopen($this->filePath, 'a+'); |
| 60 |
foreach ($data as $row) { |
| 61 |
fputcsv($this->file, $row, $this->delimiter, $this->enclosure); |
| 62 |
} |
| 63 |
fclose($this->file); |
| 64 |
} |
| 65 |
|
| 66 |
public function output($filename) |
| 67 |
{ |
| 68 |
if (!is_null($filename) && file_exists($this->filePath)) { |
| 69 |
$filename = filter_var($filename, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); |
| 70 |
header('Cache-control: private'); |
| 71 |
header('Content-Type: application/octet-stream'); |
| 72 |
header('Content-Length: '.filesize($this->filePath)); |
| 73 |
header('Content-Disposition: filename='.$filename); |
| 74 |
//Read the size of the file |
| 75 |
readfile($this->filePath); |
| 76 |
unlink($this->filePath); |
| 77 |
die(); |
| 78 |
} |
| 79 |
die('Error opening the file ' . esc_html($this->filePath)); |
| 80 |
} |
| 81 |
} |
| 82 |
|