You are here

public function EasyRdf_Parser_JsonLd::parse in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 vendor/easyrdf/easyrdf/lib/EasyRdf/Parser/JsonLdImplementation.php \EasyRdf_Parser_JsonLd::parse()

Parse a JSON-LD document into an EasyRdf_Graph

Attention: Since JSON-LD supports datasets, a document may contain multiple graphs and not just one. This parser returns only the default graph. An alternative would be to merge all graphs.

Parameters

object EasyRdf_Graph $graph the graph to load the data into:

string $data the RDF document data:

string $format the format of the input data:

string $baseUri the base URI of the data being parsed:

Return value

integer The number of triples added to the graph

Overrides EasyRdf_Parser::parse

File

vendor/easyrdf/easyrdf/lib/EasyRdf/Parser/JsonLdImplementation.php, line 61

Class

EasyRdf_Parser_JsonLd
Class to parse JSON-LD to an EasyRdf_Graph

Code

public function parse($graph, $data, $format, $baseUri) {
  parent::checkParseParams($graph, $data, $format, $baseUri);
  if ($format != 'jsonld') {
    throw new EasyRdf_Exception("EasyRdf_Parser_JsonLd does not support {$format}");
  }
  try {
    $quads = \ML\JsonLD\JsonLD::toRdf($data, array(
      'base' => $baseUri,
    ));
  } catch (\ML\JsonLD\Exception\JsonLdException $e) {
    throw new EasyRdf_Parser_Exception($e
      ->getMessage());
  }
  foreach ($quads as $quad) {

    // Ignore named graphs
    if (null !== $quad
      ->getGraph()) {
      continue;
    }
    $subject = (string) $quad
      ->getSubject();
    if ('_:' === substr($subject, 0, 2)) {
      $subject = $this
        ->remapBnode($subject);
    }
    $predicate = (string) $quad
      ->getProperty();
    if ($quad
      ->getObject() instanceof \ML\IRI\IRI) {
      $object = array(
        'type' => 'uri',
        'value' => (string) $quad
          ->getObject(),
      );
      if ('_:' === substr($object['value'], 0, 2)) {
        $object = array(
          'type' => 'bnode',
          'value' => $this
            ->remapBnode($object['value']),
        );
      }
    }
    else {
      $object = array(
        'type' => 'literal',
        'value' => $quad
          ->getObject()
          ->getValue(),
      );
      if ($quad
        ->getObject() instanceof \ML\JsonLD\LanguageTaggedString) {
        $object['lang'] = $quad
          ->getObject()
          ->getLanguage();
      }
      else {
        $object['datatype'] = $quad
          ->getObject()
          ->getType();
      }
    }
    $this
      ->addTriple($subject, $predicate, $object);
  }
  return $this->tripleCount;
}