Overview

Packages

  • CodeIgniter
    • Libraries
  • None

Classes

  • Format

Functions

  • _perform_ldap_auth
  • Overview
  • Package
  • Function
  • Tree
  • Todo
  1: <?php
  2: /**
  3:  * Format class
  4:  *
  5:  * Help convert between various formats such as XML, JSON, CSV, etc.
  6:  *
  7:  * @author      Phil Sturgeon
  8:  * @license     http://philsturgeon.co.uk/code/dbad-license
  9:  */
 10: class Format {
 11: 
 12:     // Array to convert
 13:     protected $_data = array();
 14: 
 15:     // View filename
 16:     protected $_from_type = NULL;
 17: 
 18:     /**
 19:      * Returns an instance of the Format object.
 20:      *
 21:      *     echo $this->format->factory(array('foo' => 'bar'))->to_xml();
 22:      *
 23:      * @param   mixed  general date to be converted
 24:      * @param   string  data format the file was provided in
 25:      * @return  Factory
 26:      */
 27:     public function factory($data, $from_type = NULL)
 28:     {
 29:         // Stupid stuff to emulate the "new static()" stuff in this libraries PHP 5.3 equivalent
 30:         $class = __CLASS__;
 31:         return new $class($data, $from_type);
 32:     }
 33: 
 34:     /**
 35:      * Do not use this directly, call factory()
 36:      */
 37:     public function __construct($data = NULL, $from_type = NULL)
 38:     {
 39:         get_instance()->load->helper('inflector');
 40: 
 41:         // If the provided data is already formatted we should probably convert it to an array
 42:         if ($from_type !== NULL)
 43:         {
 44:             if (method_exists($this, '_from_' . $from_type))
 45:             {
 46:                 $data = call_user_func(array($this, '_from_' . $from_type), $data);
 47:             }
 48: 
 49:             else
 50:             {
 51:                 throw new Exception('Format class does not support conversion from "' . $from_type . '".');
 52:             }
 53:         }
 54: 
 55:         $this->_data = $data;
 56:     }
 57: 
 58:     // FORMATING OUTPUT ---------------------------------------------------------
 59: 
 60:     public function to_array($data = NULL)
 61:     {
 62:         // If not just NULL, but nothing is provided
 63:         if ($data === NULL and ! func_num_args())
 64:         {
 65:             $data = $this->_data;
 66:         }
 67: 
 68:         $array = array();
 69: 
 70:         foreach ((array) $data as $key => $value)
 71:         {
 72:             if (is_object($value) or is_array($value))
 73:             {
 74:                 $array[$key] = $this->to_array($value);
 75:             }
 76: 
 77:             else
 78:             {
 79:                 $array[$key] = $value;
 80:             }
 81:         }
 82: 
 83:         return $array;
 84:     }
 85: 
 86:     // Format XML for output
 87:     public function to_xml($data = NULL, $structure = NULL, $basenode = 'xml')
 88:     {
 89:         if ($data === NULL and ! func_num_args())
 90:         {
 91:             $data = $this->_data;
 92:         }
 93: 
 94:         // turn off compatibility mode as simple xml throws a wobbly if you don't.
 95:         if (ini_get('zend.ze1_compatibility_mode') == 1)
 96:         {
 97:             ini_set('zend.ze1_compatibility_mode', 0);
 98:         }
 99: 
100:         if ($structure === NULL)
101:         {
102:             $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />");
103:         }
104: 
105:         // Force it to be something useful
106:         if ( ! is_array($data) AND ! is_object($data))
107:         {
108:             $data = (array) $data;
109:         }
110: 
111:         foreach ($data as $key => $value)
112:         {
113: 
114:             //change false/true to 0/1
115:             if(is_bool($value))
116:             {
117:                 $value = (int) $value;
118:             }
119: 
120:             // no numeric keys in our xml please!
121:             if (is_numeric($key))
122:             {
123:                 // make string key...
124:                 $key = (singular($basenode) != $basenode) ? singular($basenode) : 'item';
125:             }
126: 
127:             // replace anything not alpha numeric
128:             $key = preg_replace('/[^a-z_\-0-9]/i', '', $key);
129: 
130:             if ($key === '_attributes' && (is_array($value) || is_object($value)))
131:             {
132:                 $attributes = $value;
133:                 if (is_object($attributes)) $attributes = get_object_vars($attributes);
134: 
135:                 foreach ($attributes as $attributeName => $attributeValue)
136:                 {
137:                     $structure->addAttribute($attributeName, $attributeValue);
138:                 }
139:             }
140:             // if there is another array found recursively call this function
141:             else if (is_array($value) || is_object($value))
142:             {
143:                 $node = $structure->addChild($key);
144: 
145:                 // recursive call.
146:                 $this->to_xml($value, $node, $key);
147:             }
148:             else
149:             {
150:                 // add single node.
151:                 $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, "UTF-8");
152: 
153:                 $structure->addChild($key, $value);
154:             }
155:         }
156: 
157:         return $structure->asXML();
158:     }
159: 
160:     // Format HTML for output
161:     public function to_html()
162:     {
163:         $data = (array)$this->_data;
164: 
165:         // Multi-dimensional array
166:         if (isset($data[0]) && is_array($data[0]))
167:         {
168:             $headings = array_keys($data[0]);
169:         }
170: 
171:         // Single array
172:         else
173:         {
174:             $headings = array_keys($data);
175:             $data = array($data);
176:         }
177: 
178:         $ci = get_instance();
179:         $ci->load->library('table');
180: 
181:         $ci->table->set_heading($headings);
182: 
183:         foreach ($data as &$row)
184:         {
185:             $ci->table->add_row($row);
186:         }
187: 
188:         return $ci->table->generate();
189:     }
190: 
191:     // Format CSV for output
192:     public function to_csv()
193:     {
194:         $data = (array)$this->_data;
195: 
196:         // Multi-dimensional array
197:         if (isset($data[0]) && is_array($data[0]))
198:         {
199:             $headings = array_keys($data[0]);
200:         }
201: 
202:         // Single array
203:         else
204:         {
205:             $headings = array_keys($data);
206:             $data = array($data);
207:         }
208: 
209:         $output = '"'.implode('","', $headings).'"'.PHP_EOL;
210:         foreach ($data as &$row)
211:         {
212:                     $row    = str_replace('"', '""', $row); // Escape dbl quotes per RFC 4180
213:                     $output .= '"'.implode('","', $row).'"'.PHP_EOL;
214:         }
215: 
216:         return $output;
217:     }
218: 
219:     // Encode as JSON
220:     public function to_json()
221:     {
222:         $callback = isset($_GET['callback']) ? $_GET['callback'] : '';
223:         if ($callback === '')
224:         {
225:             return json_encode($this->_data);
226: 
227:             /* Had to take out this code, it doesn't work on Objects.
228:             $str = $this->_data;
229:             array_walk_recursive($str, function(&$item, $key)
230:             {
231:                 if(!mb_detect_encoding($item, 'utf-8', true))
232:                 {
233:                     $item = utf8_encode($item);
234:                 }
235:             });
236: 
237:             return json_encode($str);
238:             */
239:         }
240: 
241:         // we only honour jsonp callback which are valid javascript identifiers
242:         else if (preg_match('/^[a-z_\$][a-z0-9\$_]*(\.[a-z_\$][a-z0-9\$_]*)*$/i', $callback))
243:         {
244:             // this is a jsonp request, the content-type must be updated to be text/javascript
245:             header("Content-Type: application/javascript");
246:             return $callback . "(" . json_encode($this->_data) . ");";
247:         }
248:         else
249:         {
250:             // we have an invalid jsonp callback identifier, we'll return plain json with a warning field
251:             $this->_data['warning'] = "invalid jsonp callback provided: ".$callback;
252:             return json_encode($this->_data);
253:         }
254:     }
255: 
256:     // Encode as Serialized array
257:     public function to_serialized()
258:     {
259:         return serialize($this->_data);
260:     }
261: 
262:     // Output as a string representing the PHP structure
263:     public function to_php()
264:     {
265:         return var_export($this->_data, TRUE);
266:     }
267: 
268:     // Format XML for output
269:     protected function _from_xml($string)
270:     {
271:         return $string ? (array) simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA) : array();
272:     }
273: 
274:     // Format CSV for output
275:     // This function is DODGY! Not perfect CSV support but works with my REST_Controller
276:     protected function _from_csv($string)
277:     {
278:         $data = array();
279: 
280:         // Splits
281:         $rows = explode("\n", trim($string));
282:         $headings = explode(',', array_shift($rows));
283:         foreach ($rows as $row)
284:         {
285:             // The substr removes " from start and end
286:             $data_fields = explode('","', trim(substr($row, 1, -1)));
287: 
288:             if (count($data_fields) == count($headings))
289:             {
290:                 $data[] = array_combine($headings, $data_fields);
291:             }
292:         }
293: 
294:         return $data;
295:     }
296: 
297:     // Encode as JSON
298:     private function _from_json($string)
299:     {
300:         return json_decode(trim($string));
301:     }
302: 
303:     // Encode as Serialized array
304:     private function _from_serialize($string)
305:     {
306:         return unserialize(trim($string));
307:     }
308: 
309:     // If you provide text/plain value on the Content-type header on a request
310:     // just return the string
311:     private function _from_php($string)
312:     {
313:         return trim($string);
314:     }
315: 
316: }
317: 
318: /* End of file format.php */
319: 
API documentation generated by ApiGen