PageRenderTime 43ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/application/libraries/Format.php

https://bitbucket.org/paulkish/no-cms
PHP | 270 lines | 167 code | 50 blank | 53 comment | 20 complexity | 65aeea1f160353eca398375bcb1c1124 MD5 | raw file
  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. // Array to convert
  12. protected $_data = array();
  13. // View filename
  14. protected $_from_type = null;
  15. /**
  16. * Returns an instance of the Format object.
  17. *
  18. * echo $this->format->factory(array('foo' => 'bar'))->to_xml();
  19. *
  20. * @param mixed general date to be converted
  21. * @param string data format the file was provided in
  22. * @return Factory
  23. */
  24. public function factory($data, $from_type = null)
  25. {
  26. // Stupid stuff to emulate the "new static()" stuff in this libraries PHP 5.3 equivalent
  27. $class = __CLASS__;
  28. return new $class($data, $from_type);
  29. }
  30. /**
  31. * Do not use this directly, call factory()
  32. */
  33. public function __construct($data = null, $from_type = null)
  34. {
  35. get_instance()->load->helper('inflector');
  36. // If the provided data is already formatted we should probably convert it to an array
  37. if ($from_type !== null)
  38. {
  39. if (method_exists($this, '_from_' . $from_type))
  40. {
  41. $data = call_user_func(array($this, '_from_' . $from_type), $data);
  42. }
  43. else
  44. {
  45. throw new Exception('Format class does not support conversion from "' . $from_type . '".');
  46. }
  47. }
  48. $this->_data = $data;
  49. }
  50. // FORMATING OUTPUT ---------------------------------------------------------
  51. public function to_array($data = null)
  52. {
  53. // If not just null, but nothing is provided
  54. if ($data === null and ! func_num_args())
  55. {
  56. $data = $this->_data;
  57. }
  58. $array = array();
  59. foreach ((array) $data as $key => $value)
  60. {
  61. if (is_object($value) or is_array($value))
  62. {
  63. $array[$key] = $this->to_array($value);
  64. }
  65. else
  66. {
  67. $array[$key] = $value;
  68. }
  69. }
  70. return $array;
  71. }
  72. // Format XML for output
  73. public function to_xml($data = null, $structure = null, $basenode = 'xml')
  74. {
  75. if ($data === null and ! func_num_args())
  76. {
  77. $data = $this->_data;
  78. }
  79. // turn off compatibility mode as simple xml throws a wobbly if you don't.
  80. if (ini_get('zend.ze1_compatibility_mode') == 1)
  81. {
  82. ini_set('zend.ze1_compatibility_mode', 0);
  83. }
  84. if ($structure === null)
  85. {
  86. $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />");
  87. }
  88. // Force it to be something useful
  89. if ( ! is_array($data) AND ! is_object($data))
  90. {
  91. $data = (array) $data;
  92. }
  93. foreach ($data as $key => $value)
  94. {
  95. //change false/true to 0/1
  96. if(is_bool($value))
  97. {
  98. $value = (int) $value;
  99. }
  100. // no numeric keys in our xml please!
  101. if (is_numeric($key))
  102. {
  103. // make string key...
  104. $key = (singular($basenode) != $basenode) ? singular($basenode) : 'item';
  105. }
  106. // replace anything not alpha numeric
  107. $key = preg_replace('/[^a-z_\-0-9]/i', '', $key);
  108. // if there is another array found recursively call this function
  109. if (is_array($value) || is_object($value))
  110. {
  111. $node = $structure->addChild($key);
  112. // recursive call.
  113. $this->to_xml($value, $node, $key);
  114. }
  115. else
  116. {
  117. // add single node.
  118. $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, "UTF-8");
  119. $structure->addChild($key, $value);
  120. }
  121. }
  122. return $structure->asXML();
  123. }
  124. // Format HTML for output
  125. public function to_html()
  126. {
  127. $data = $this->_data;
  128. // Multi-dimensional array
  129. if (isset($data[0]) && is_array($data[0]))
  130. {
  131. $headings = array_keys($data[0]);
  132. }
  133. // Single array
  134. else
  135. {
  136. $headings = array_keys($data);
  137. $data = array($data);
  138. }
  139. $ci = get_instance();
  140. $ci->load->library('table');
  141. $ci->table->set_heading($headings);
  142. foreach ($data as &$row)
  143. {
  144. $ci->table->add_row($row);
  145. }
  146. return $ci->table->generate();
  147. }
  148. // Format CSV for output
  149. public function to_csv()
  150. {
  151. $data = $this->_data;
  152. // Multi-dimensional array
  153. if (isset($data[0]) && is_array($data[0]))
  154. {
  155. $headings = array_keys($data[0]);
  156. }
  157. // Single array
  158. else
  159. {
  160. $headings = array_keys($data);
  161. $data = array($data);
  162. }
  163. $output = implode(',', $headings).PHP_EOL;
  164. foreach ($data as &$row)
  165. {
  166. $output .= '"'.implode('","', $row).'"'.PHP_EOL;
  167. }
  168. return $output;
  169. }
  170. // Encode as JSON
  171. public function to_json()
  172. {
  173. return json_encode($this->_data);
  174. }
  175. // Encode as Serialized array
  176. public function to_serialized()
  177. {
  178. return serialize($this->_data);
  179. }
  180. // Output as a string representing the PHP structure
  181. public function to_php()
  182. {
  183. return var_export($this->_data, TRUE);
  184. }
  185. // Format XML for output
  186. protected function _from_xml($string)
  187. {
  188. return $string ? (array) simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA) : array();
  189. }
  190. // Format CSV for output
  191. // This function is DODGY! Not perfect CSV support but works with my REST_Controller
  192. protected function _from_csv($string)
  193. {
  194. $data = array();
  195. // Splits
  196. $rows = explode("\n", trim($string));
  197. $headings = explode(',', array_shift($rows));
  198. foreach ($rows as $row)
  199. {
  200. // The substr removes " from start and end
  201. $data_fields = explode('","', trim(substr($row, 1, -1)));
  202. if (count($data_fields) == count($headings))
  203. {
  204. $data[] = array_combine($headings, $data_fields);
  205. }
  206. }
  207. return $data;
  208. }
  209. // Encode as JSON
  210. private function _from_json($string)
  211. {
  212. return json_decode(trim($string));
  213. }
  214. // Encode as Serialized array
  215. private function _from_serialize($string)
  216. {
  217. return unserialize(trim($string));
  218. }
  219. }
  220. /* End of file format.php */