Serialization.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. <?php
  2. /**
  3. * @package ActiveRecord
  4. */
  5. namespace ActiveRecord;
  6. use XmlWriter;
  7. /**
  8. * Base class for Model serializers.
  9. *
  10. * All serializers support the following options:
  11. *
  12. * <ul>
  13. * <li><b>only:</b> a string or array of attributes to be included.</li>
  14. * <li><b>except:</b> a string or array of attributes to be excluded.</li>
  15. * <li><b>methods:</b> a string or array of methods to invoke. The method's name will be used as a key for the final attributes array
  16. * along with the method's returned value</li>
  17. * <li><b>include:</b> a string or array of associated models to include in the final serialized product.</li>
  18. * <li><b>only_method:</b> a method that's called and only the resulting array is serialized
  19. * <li><b>skip_instruct:</b> set to true to skip the <?xml ...?> declaration.</li>
  20. * </ul>
  21. *
  22. * Example usage:
  23. *
  24. * <code>
  25. * # include the attributes id and name
  26. * # run $model->encoded_description() and include its return value
  27. * # include the comments association
  28. * # include posts association with its own options (nested)
  29. * $model->to_json(array(
  30. * 'only' => array('id','name', 'encoded_description'),
  31. * 'methods' => array('encoded_description'),
  32. * 'include' => array('comments', 'posts' => array('only' => 'id'))
  33. * ));
  34. *
  35. * # except the password field from being included
  36. * $model->to_xml(array('except' => 'password')));
  37. * </code>
  38. *
  39. * @package ActiveRecord
  40. * @link http://www.phpactiverecord.org/guides/utilities#topic-serialization
  41. */
  42. abstract class Serialization
  43. {
  44. protected $model;
  45. protected $options;
  46. protected $attributes;
  47. /**
  48. * The default format to serialize DateTime objects to.
  49. *
  50. * @see DateTime
  51. */
  52. public static $DATETIME_FORMAT = 'iso8601';
  53. /**
  54. * Set this to true if the serializer needs to create a nested array keyed
  55. * on the name of the included classes such as for xml serialization.
  56. *
  57. * Setting this to true will produce the following attributes array when
  58. * the include option was used:
  59. *
  60. * <code>
  61. * $user = array('id' => 1, 'name' => 'Tito',
  62. * 'permissions' => array(
  63. * 'permission' => array(
  64. * array('id' => 100, 'name' => 'admin'),
  65. * array('id' => 101, 'name' => 'normal')
  66. * )
  67. * )
  68. * );
  69. * </code>
  70. *
  71. * Setting to false will produce this:
  72. *
  73. * <code>
  74. * $user = array('id' => 1, 'name' => 'Tito',
  75. * 'permissions' => array(
  76. * array('id' => 100, 'name' => 'admin'),
  77. * array('id' => 101, 'name' => 'normal')
  78. * )
  79. * );
  80. * </code>
  81. *
  82. * @var boolean
  83. */
  84. protected $includes_with_class_name_element = false;
  85. /**
  86. * Constructs a {@link Serialization} object.
  87. *
  88. * @param Model $model The model to serialize
  89. * @param array &$options Options for serialization
  90. * @return Serialization
  91. */
  92. public function __construct(Model $model, &$options)
  93. {
  94. $this->model = $model;
  95. $this->options = $options;
  96. $this->attributes = $model->attributes();
  97. $this->parse_options();
  98. }
  99. private function parse_options()
  100. {
  101. $this->check_only();
  102. $this->check_except();
  103. $this->check_methods();
  104. $this->check_include();
  105. $this->check_only_method();
  106. }
  107. private function check_only()
  108. {
  109. if (isset($this->options['only']))
  110. {
  111. $this->options_to_a('only');
  112. $exclude = array_diff(array_keys($this->attributes),$this->options['only']);
  113. $this->attributes = array_diff_key($this->attributes,array_flip($exclude));
  114. }
  115. }
  116. private function check_except()
  117. {
  118. if (isset($this->options['except']) && !isset($this->options['only']))
  119. {
  120. $this->options_to_a('except');
  121. $this->attributes = array_diff_key($this->attributes,array_flip($this->options['except']));
  122. }
  123. }
  124. private function check_methods()
  125. {
  126. if (isset($this->options['methods']))
  127. {
  128. $this->options_to_a('methods');
  129. foreach ($this->options['methods'] as $method)
  130. {
  131. if (method_exists($this->model, $method))
  132. $this->attributes[$method] = $this->model->$method();
  133. }
  134. }
  135. }
  136. private function check_only_method()
  137. {
  138. if (isset($this->options['only_method']))
  139. {
  140. $method = $this->options['only_method'];
  141. if (method_exists($this->model, $method))
  142. $this->attributes = $this->model->$method();
  143. }
  144. }
  145. private function check_include()
  146. {
  147. if (isset($this->options['include']))
  148. {
  149. $this->options_to_a('include');
  150. $serializer_class = get_class($this);
  151. foreach ($this->options['include'] as $association => $options)
  152. {
  153. if (!is_array($options))
  154. {
  155. $association = $options;
  156. $options = array();
  157. }
  158. try {
  159. $assoc = $this->model->$association;
  160. if (!is_array($assoc))
  161. {
  162. $serialized = new $serializer_class($assoc, $options);
  163. $this->attributes[$association] = $serialized->to_a();;
  164. }
  165. else
  166. {
  167. $includes = array();
  168. foreach ($assoc as $a)
  169. {
  170. $serialized = new $serializer_class($a, $options);
  171. if ($this->includes_with_class_name_element)
  172. $includes[strtolower(get_class($a))][] = $serialized->to_a();
  173. else
  174. $includes[] = $serialized->to_a();
  175. }
  176. $this->attributes[$association] = $includes;
  177. }
  178. } catch (UndefinedPropertyException $e) {
  179. ;//move along
  180. }
  181. }
  182. }
  183. }
  184. final protected function options_to_a($key)
  185. {
  186. if (!is_array($this->options[$key]))
  187. $this->options[$key] = array($this->options[$key]);
  188. }
  189. /**
  190. * Returns the attributes array.
  191. * @return array
  192. */
  193. final public function to_a()
  194. {
  195. foreach ($this->attributes as &$value)
  196. {
  197. if ($value instanceof \DateTime)
  198. $value = $value->format(self::$DATETIME_FORMAT);
  199. }
  200. return $this->attributes;
  201. }
  202. /**
  203. * Returns the serialized object as a string.
  204. * @see to_s
  205. * @return string
  206. */
  207. final public function __toString()
  208. {
  209. return $this->to_s();
  210. }
  211. /**
  212. * Performs the serialization.
  213. * @return string
  214. */
  215. abstract public function to_s();
  216. };
  217. /**
  218. * Array serializer.
  219. *
  220. * @package ActiveRecord
  221. */
  222. class ArraySerializer extends Serialization
  223. {
  224. public static $include_root = false;
  225. public function to_s()
  226. {
  227. return self::$include_root ? array(strtolower(get_class($this->model)) => $this->to_a()) : $this->to_a();
  228. }
  229. }
  230. /**
  231. * JSON serializer.
  232. *
  233. * @package ActiveRecord
  234. */
  235. class JsonSerializer extends ArraySerializer
  236. {
  237. public static $include_root = false;
  238. public function to_s()
  239. {
  240. parent::$include_root = self::$include_root;
  241. return json_encode(parent::to_s());
  242. }
  243. }
  244. /**
  245. * XML serializer.
  246. *
  247. * @package ActiveRecord
  248. */
  249. class XmlSerializer extends Serialization
  250. {
  251. private $writer;
  252. public function __construct(Model $model, &$options)
  253. {
  254. $this->includes_with_class_name_element = true;
  255. parent::__construct($model,$options);
  256. }
  257. public function to_s()
  258. {
  259. return $this->xml_encode();
  260. }
  261. private function xml_encode()
  262. {
  263. $this->writer = new XmlWriter();
  264. $this->writer->openMemory();
  265. $this->writer->startDocument('1.0', 'UTF-8');
  266. $this->writer->startElement(strtolower(denamespace(($this->model))));
  267. $this->write($this->to_a());
  268. $this->writer->endElement();
  269. $this->writer->endDocument();
  270. $xml = $this->writer->outputMemory(true);
  271. if (@$this->options['skip_instruct'] == true)
  272. $xml = preg_replace('/<\?xml version.*?\?>/','',$xml);
  273. return $xml;
  274. }
  275. private function write($data, $tag=null)
  276. {
  277. foreach ($data as $attr => $value)
  278. {
  279. if ($tag != null)
  280. $attr = $tag;
  281. if (is_array($value) || is_object($value))
  282. {
  283. if (!is_int(key($value)))
  284. {
  285. $this->writer->startElement($attr);
  286. $this->write($value);
  287. $this->writer->endElement();
  288. }
  289. else
  290. $this->write($value, $attr);
  291. continue;
  292. }
  293. $this->writer->writeElement($attr, $value);
  294. }
  295. }
  296. }
  297. /**
  298. * CSV serializer.
  299. *
  300. * @package ActiveRecord
  301. */
  302. class CsvSerializer extends Serialization
  303. {
  304. public static $delimiter = ',';
  305. public static $enclosure = '"';
  306. public function to_s()
  307. {
  308. if (@$this->options['only_header'] == true) return $this->header();
  309. return $this->row();
  310. }
  311. private function header()
  312. {
  313. return $this->to_csv(array_keys($this->to_a()));
  314. }
  315. private function row()
  316. {
  317. return $this->to_csv($this->to_a());
  318. }
  319. private function to_csv($arr)
  320. {
  321. $outstream = fopen('php://temp', 'w');
  322. fputcsv($outstream, $arr, self::$delimiter, self::$enclosure);
  323. rewind($outstream);
  324. $buffer = trim(stream_get_contents($outstream));
  325. fclose($outstream);
  326. return $buffer;
  327. }
  328. }
  329. ?>