123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188 |
- <?php
- class XML_XRD_Loader_JSON
- {
-
- protected $xrd;
-
- public function __construct(XML_XRD $xrd)
- {
- $this->xrd = $xrd;
- }
-
- public function loadFile($file)
- {
- $json = file_get_contents($file);
- if ($json === false) {
- throw new XML_XRD_Loader_Exception(
- 'Error loading JRD file: ' . $file,
- XML_XRD_Loader_Exception::LOAD
- );
- }
- return $this->loadString($json);
- }
-
- public function loadString($json)
- {
- if ($json == '') {
- throw new XML_XRD_Loader_Exception(
- 'Error loading JRD: string empty',
- XML_XRD_Loader_Exception::LOAD
- );
- }
- $obj = json_decode($json);
- if ($obj !== null) {
- return $this->load($obj);
- }
- $constants = get_defined_constants(true);
- $json_errors = array();
- foreach ($constants['json'] as $name => $value) {
- if (!strncmp($name, 'JSON_ERROR_', 11)) {
- $json_errors[$value] = $name;
- }
- }
- throw new XML_XRD_Loader_Exception(
- 'Error loading JRD: ' . $json_errors[json_last_error()],
- XML_XRD_Loader_Exception::LOAD
- );
- }
-
- public function load(stdClass $j)
- {
- if (isset($j->subject)) {
- $this->xrd->subject = (string)$j->subject;
- }
- if (isset($j->aliases)) {
- foreach ($j->aliases as $jAlias) {
- $this->xrd->aliases[] = (string)$jAlias;
- }
- }
- if (isset($j->links)) {
- foreach ($j->links as $jLink) {
- $this->xrd->links[] = $this->loadLink($jLink);
- }
- }
- $this->loadProperties($this->xrd, $j);
- if (isset($j->expires)) {
- $this->xrd->expires = strtotime($j->expires);
- }
- }
-
- protected function loadProperties(
- XML_XRD_PropertyAccess $store, stdClass $j
- ) {
- if (!isset($j->properties)) {
- return true;
- }
- foreach ($j->properties as $type => $jProp) {
- $store->properties[] = new XML_XRD_Element_Property(
- $type, (string)$jProp
- );
- }
-
- return true;
- }
-
- protected function loadLink(stdClass $j)
- {
- $link = new XML_XRD_Element_Link();
- foreach (array('rel', 'type', 'href', 'template') as $var) {
- if (isset($j->$var)) {
- $link->$var = (string)$j->$var;
- }
- }
- if (isset($j->titles)) {
- foreach ($j->titles as $lang => $jTitle) {
- if (!isset($link->titles[$lang])) {
- $link->titles[$lang] = (string)$jTitle;
- }
- }
- }
- $this->loadProperties($link, $j);
- return $link;
- }
- }
- ?>
|