| <?php |
|
|
| namespace Kanboard\Core; |
|
|
| use SplFileObject; |
|
|
| |
| |
| |
| |
| |
| |
| class Csv |
| { |
| |
| |
| |
| |
| |
| |
| private $delimiter = ','; |
|
|
| |
| |
| |
| |
| |
| |
| private $enclosure = '"'; |
|
|
| |
| |
| |
| |
| |
| |
| private $columns = array(); |
|
|
| |
| |
| |
| |
| |
| |
| |
| public function __construct($delimiter = ',', $enclosure = '"') |
| { |
| $this->delimiter = $delimiter; |
| $this->enclosure = $enclosure; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| public static function getDelimiters() |
| { |
| return array( |
| ',' => t('Comma'), |
| ';' => t('Semi-colon'), |
| '\t' => t('Tab'), |
| '|' => t('Vertical bar'), |
| ); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| public static function getEnclosures() |
| { |
| return array( |
| '"' => t('Double Quote'), |
| "'" => t('Single Quote'), |
| '' => t('None'), |
| ); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| public static function getBooleanValue($value) |
| { |
| if (! empty($value)) { |
| $value = trim(strtolower($value)); |
| return $value === '1' || $value[0] === 't' || $value[0] === 'y' ? 1 : 0; |
| } |
|
|
| return 0; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| public static function output(array $rows) |
| { |
| $csv = new static; |
| $csv->write('php://output', $rows); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| public function setColumnMapping(array $columns) |
| { |
| $this->columns = $columns; |
| return $this; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| public function read($filename, $callback) |
| { |
| $file = new SplFileObject($filename); |
| $file->setFlags(SplFileObject::READ_CSV); |
| $file->setCsvControl($this->delimiter, $this->enclosure); |
| $line_number = 0; |
|
|
| foreach ($file as $row) { |
| $row = $this->filterRow($row); |
|
|
| if (! empty($row) && $line_number > 0) { |
| call_user_func_array($callback, array($this->associateColumns($row), $line_number)); |
| } |
|
|
| $line_number++; |
| } |
|
|
| return $this; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| public function write($filename, array $rows) |
| { |
| $fp = fopen($filename, 'w'); |
|
|
| if (is_resource($fp)) { |
| foreach ($rows as $row) { |
| fputcsv($fp, $row, $this->delimiter, $this->enclosure); |
| } |
|
|
| fclose($fp); |
| } |
|
|
| return $this; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| private function associateColumns(array $row) |
| { |
| $line = array(); |
| $index = 0; |
|
|
| foreach ($this->columns as $sql_name => $csv_name) { |
| if (isset($row[$index])) { |
| $line[$sql_name] = $row[$index]; |
| } else { |
| $line[$sql_name] = ''; |
| } |
|
|
| $index++; |
| } |
|
|
| return $line; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| private function filterRow(array $row) |
| { |
| return array_filter($row); |
| } |
| } |
|
|