Overview

Namespaces

  • Sleepy
  • Module
    • Authentication
    • CSV
    • DB
    • FormBuilder
    • FSDB
    • IP2Country
    • Mailer
    • MobiDetect
    • Navigation
    • StaticCache
  • PHP

Classes

  • Sleepy\Debug
  • Sleepy\Hook
  • Sleepy\Router
  • Sleepy\SM
  • Sleepy\Template

Exceptions

  • Sleepy\RouteNotFound
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  • Todo
  1: <?php
  2: namespace Module\CSV;
  3: 
  4: /**
  5:  * Creates a Comma Separated Value file.
  6:  *
  7:  * ### Usage
  8:  *
  9:  * <code>
 10:  *   // loads a existing CSV file
 11:  *   $c = new \Module\CSV\Document('presidents.csv');
 12:  *
 13:  *   $c->add(array(
 14:  *     'George',
 15:  *     'Washington'
 16:  *   ));
 17:  *
 18:  *   $c->save();
 19:  * </code>
 20:  *
 21:  * ### Changelog
 22:  *
 23:  * ##Version 1.8
 24:  * * Added namespacing
 25:  * * Renamed remove method to delete
 26:  * * Added a search method
 27:  *
 28:  * ##Version 1.6
 29:  * * Updated documentation
 30:  *
 31:  * ##Version 1.5
 32:  * * check if we can remove the header before doing it... teamsite issue.
 33:  * * suppress flock warnings... teamsite issue
 34:  *
 35:  * @date August 13, 2014
 36:  * @author Jaime A. Rodriguez <hi.i.am.jaime@gmail.com>
 37:  * @version 1.8
 38:  * @license  http://opensource.org/licenses/MIT
 39:  */
 40: class Document {
 41:     /**
 42:      * string The filename of the CSV file
 43:      */
 44:     public $filename = '';
 45: 
 46: 
 47:     /**
 48:      * string Define what character to use as a delimiter
 49:      */
 50:     public $delimiter = ',';
 51: 
 52: 
 53:     /**
 54:      * mixed The data gets stored here while "in utero"
 55:      */
 56:     public $data;
 57: 
 58:     /**
 59:      * Constructor
 60:      *
 61:      * @param string $filename
 62:      *   (optional) if set, loads the file
 63:      */
 64:     public function __construct($filename='') {
 65:         if ($filename != '') {
 66:             $this->load($filename);
 67:         }
 68:     }
 69: 
 70:     /**
 71:      * Loads an existing CSV file into $this->data
 72:      *
 73:      * @param string $filename
 74:      *   (optional) Name of file. If it is not set, then it uses
 75:      *   $this->filename instead.
 76:      * @return bool
 77:      *   Returns true if successful.
 78:      */
 79:     public function load($filename='') {
 80:         if ($filename != '') {
 81:             $this->filename = $filename;
 82:         } else {
 83:             if ($this->filename == '') {
 84:                 throw new \Exception('CSV::load - Cannot save without a filename.');
 85:             }
 86:         }
 87: 
 88:         $this->data = array();
 89: 
 90:         // If the file does not exist, create it.
 91:         if (!file_exists($this->filename)) {
 92:             file_put_contents($this->filename, '');
 93:         }
 94: 
 95:         if (($handle = @fopen($this->filename, "r+")) !== FALSE) {
 96:             flock($handle, LOCK_EX);
 97:             while (($data = fgetcsv($handle, 0, $this->delimiter)) !== FALSE) {
 98:                 $this->data[] = $data;
 99:                 $num = count($data);
100:             }
101:             flock($handle, LOCK_UN);
102:             fclose($handle);
103:             $numberOfFields = count($data);
104:         } else {
105:             throw new \Exception('CSV::load - Cannot open file for writing');
106:         }
107: 
108:         return true;
109:     }
110: 
111:     /**
112:      * Saves the CSV file.
113:      *
114:      * @param string $filename
115:      *   (optional) Name of file. If it is not set, then it uses
116:      *   $this->filename instead.
117:      * @return bool
118:      *   Returns true if successful.
119:      */
120:     public function save($filename='') {
121:         if ($filename != '') {
122:             $this->filename = $filename;
123:         } else {
124:             if ($this->filename == '') {
125:                 throw new \Exception('CSV::save - Cannot save without a filename.');
126:             }
127:         }
128: 
129:         // make the file if it doesn't exist.
130:         if (!file_exists($this->filename)) {
131:             file_put_contents($this->filename, '');
132:         }
133: 
134:         if ($handle = @fopen($this->filename, 'r+')) {
135:             @flock($handle, LOCK_EX);
136:             foreach ($this->data as $row) {
137:                 fputcsv($handle, $row);
138:             }
139:             @flock($handle, LOCK_UN);
140:             fclose($handle);
141:         } else {
142:             throw new \Exception("CSV::save - Cannot open file ({$filename}) for writing");
143:         }
144: 
145:         return true;
146:     }
147: 
148:     /**
149:      * Adds a new line to the CSV file
150:      *
151:      * @param mixed $array
152:      *   An array of values.
153:      * @return bool
154:      *   Returns true if successful.
155:      */
156:     public function add($array) {
157:         if (!is_array($array)) {
158:             throw new \Exception('CSV::add - Parameter must be an array.');
159:         }
160: 
161:         if (count($array) == count($array, COUNT_RECURSIVE)) {
162:             $this->data[] = $array;
163:         } else {
164:             foreach ($array as $record) {
165:                 $this->data[] = $record;
166:             }
167:         }
168: 
169:         return true;
170:     }
171: 
172:     /**
173:      * Deletes a line from the CSV file
174:      *
175:      * @param int $id
176:      *   The array key to remove from $this->data.
177:      * @return bool
178:      *   Returns true if successful.
179:      */
180:     public function delete($id) {
181:         if (isset($this->data[$id])) {
182:             unset($this->data[$id]);
183:             return true;
184:         } else {
185:             throw new \Exception('CSV::delete - Row does not exist. Data not removed.');
186:         }
187:     }
188: 
189:     /**
190:      * Search through the CSV for a string and return an associative array of
191:      * array_index => array()
192:      *
193:      * @param  string  $string        The string to search for
194:      * @param  boolean $partial       If true, return partial matches
195:      * @param  boolean $caseSensitive If true, search is case sensitive
196:      * @return array                  An array of matching data
197:      */
198:     public function search($string, $partial=false, $caseSensitive=true) {
199:         $matches = array();
200: 
201:         if (!$caseSensitive) {
202:             $string = strtolower($value);
203:         }
204: 
205:         foreach ($this->data as $id => $row) {
206:             foreach ($row as $value) {
207:                 if (!$caseSensitive) {
208:                     $value = strtolower($value);
209:                 }
210: 
211:                 $match = strpos($value, $string);
212: 
213:                 if (!$partial) {
214:                     if ($match === 0) {
215:                         $matches[$id] = $row;
216:                     }
217:                 } else {
218:                     if ($match !== false) {
219:                         $matches[$id] = $row;
220:                     }
221:                 }
222:             }
223:         }
224: 
225:         return $matches;
226:     }
227: 
228:     /**
229:      * Instead of saving the file, it outputs to default output with headers.
230:      */
231:     public function show() {
232:         ob_end_clean();
233: 
234:         // Name the file
235:         $filename = date('YmdHis') . ".csv";
236: 
237:         // Write the CSV headers
238:         if (function_exists('header_remove')) {
239:             header_remove();
240:         }
241: 
242:         header("Pragma: public");
243:         header("Expires: 0");
244:         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
245:         header("Cache-Control: private", false);
246:         header("Content-Type: application/octet-stream");
247:         header("Content-Disposition: attachment; filename=\"$filename\";" );
248:         header("Content-Transfer-Encoding: binary");
249: 
250:         // output of csv to default output (screen) instead of a file
251:         $this->filename = "php://output";
252: 
253:         $this->save();
254:     }
255: }
sleepyMUSTACHE v.0.8 API documentation generated by ApiGen