JSON.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Part of XML_XRD
  4. *
  5. * PHP version 5
  6. *
  7. * @category XML
  8. * @package XML_XRD
  9. * @author Christian Weiske <cweiske@php.net>
  10. * @license http://www.gnu.org/copyleft/lesser.html LGPL
  11. * @link http://pear.php.net/package/XML_XRD
  12. */
  13. /**
  14. * Generate JSON from a XML_XRD object (for JRD files).
  15. *
  16. * @category XML
  17. * @package XML_XRD
  18. * @author Christian Weiske <cweiske@php.net>
  19. * @license http://www.gnu.org/copyleft/lesser.html LGPL
  20. * @version Release: @package_version@
  21. * @link http://pear.php.net/package/XML_XRD
  22. * @link http://tools.ietf.org/html/rfc6415#appendix-A
  23. */
  24. class XML_XRD_Serializer_JSON
  25. {
  26. protected $xrd;
  27. /**
  28. * Create new instance
  29. *
  30. * @param XML_XRD $xrd XRD instance to convert to JSON
  31. */
  32. public function __construct(XML_XRD $xrd)
  33. {
  34. $this->xrd = $xrd;
  35. }
  36. /**
  37. * Generate JSON.
  38. *
  39. * @return string JSON code
  40. */
  41. public function __toString()
  42. {
  43. $o = new stdClass();
  44. if ($this->xrd->expires !== null) {
  45. $o->expires = gmdate('Y-m-d\TH:i:s\Z', $this->xrd->expires);
  46. }
  47. if ($this->xrd->subject !== null) {
  48. $o->subject = $this->xrd->subject;
  49. }
  50. foreach ($this->xrd->aliases as $alias) {
  51. $o->aliases[] = $alias;
  52. }
  53. foreach ($this->xrd->properties as $property) {
  54. $o->properties[$property->type] = $property->value;
  55. }
  56. $o->links = array();
  57. foreach ($this->xrd->links as $link) {
  58. $lid = count($o->links);
  59. $o->links[$lid] = new stdClass();
  60. if ($link->rel) {
  61. $o->links[$lid]->rel = $link->rel;
  62. }
  63. if ($link->type) {
  64. $o->links[$lid]->type = $link->type;
  65. }
  66. if ($link->href) {
  67. $o->links[$lid]->href = $link->href;
  68. }
  69. if ($link->template !== null && $link->href === null) {
  70. $o->links[$lid]->template = $link->template;
  71. }
  72. foreach ($link->titles as $lang => $value) {
  73. if ($lang == null) {
  74. $lang = 'default';
  75. }
  76. $o->links[$lid]->titles[$lang] = $value;
  77. }
  78. foreach ($link->properties as $property) {
  79. $o->links[$lid]->properties[$property->type] = $property->value;
  80. }
  81. }
  82. if (count($o->links) == 0) {
  83. unset($o->links);
  84. }
  85. return json_encode($o);
  86. }
  87. }
  88. ?>