initial commit
[namibia] / module / Utility / src / Utility / Export / Csv.php
1 <?php
2 namespace Utility\Export;
3
4 class Csv
5 {
6         private $_file;
7         private $_fileHandle;
8         private $_delimiter = ',';
9         private $_enclosure = '"';
10         private $_escape = '\\';
11         private $_recordLength = 0;
12
13         const WRITE_OVERWRITE   = 1;
14         const WRITE_APPEND              = 2;
15
16         public function __construct($file, $writeMethod = self::WRITE_OVERWRITE)
17         {
18                 $this->_file = $file;
19                 $method = self::WRITE_OVERWRITE == $writeMethod
20                         ? 'w'
21                         : 'a';
22                 $this->_fileHandle = fopen($this->_file, $method);
23                 if (!$this->_fileHandle)
24                 {
25                         throw new \Exception('File ' . $this->_file . ' could not be opened for writing');
26                 }
27         }
28
29         public function setDelimiter($delimiter)
30         {
31                 $this->_delimiter = $delimiter;
32                 if (!empty($this->_headers))
33                 {
34                         $this->reset();
35                         $this->_headers = $this->getRecord(self::FETCH_LAZY);
36                 }
37         }
38
39         public function setEnclosure($enclosure)
40         {
41                 $this->_enclosure = $enclosure;
42         }
43
44         public function setEscape($escape)
45         {
46                 $this->_escape = $escape;
47         }
48
49         public function setRecordLength($length)
50         {
51                 $this->_recordLength = $length;
52         }
53
54         /**
55          * Writes a record to the file
56          * @return array
57          */
58         public function putRecord($record)
59         {
60                 $bytesWritten = fputcsv($this->_fileHandle, $record, $this->_delimiter, $this->_enclosure);
61                 return 0 < $bytesWritten
62                         ? true
63                         : false;
64         }
65
66         public function __destruct()
67         {
68                 if ($this->_fileHandle)
69                 {
70                         fclose($this->_fileHandle);
71                 }
72         }
73 }