Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Json Ld Laravel Package

sweetrdf/json-ld

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sweetrdf/json-ld
    

    Ensure your project uses PHP 8.1+.

  2. First Use Case: Load and expand a JSON-LD document:

    use SweetRdf\JsonLD\JsonLD;
    
    $expanded = JsonLD::expand(file_get_contents('data.jsonld'));
    echo JsonLD::toString($expanded, true); // Pretty-print
    
  3. Where to Look First:

    • API Docs: The official JSON-LD API is fully supported.
    • Source Code: Classes are well-documented; start with src/JsonLD.php for core methods.
    • Test Suite: The official JSON-LD tests are passed—useful for edge cases.

Implementation Patterns

Core Workflows

  1. Data Transformation:

    • Expand: Convert nested JSON-LD to flat RDF triples.
      $expanded = JsonLD::expand($jsonLdString);
      
    • Compact: Apply a context to normalize output.
      $compacted = JsonLD::compact($jsonLdString, file_get_contents('context.jsonld'));
      
    • Frame: Extract specific data using a frame.
      $framed = JsonLD::frame($jsonLdString, file_get_contents('frame.jsonld'));
      
  2. RDF Conversion:

    • Convert JSON-LD to RDF quads (for SPARQL or storage):
      $quads = JsonLD::toRdf($jsonLdString);
      $nquads = new \SweetRdf\Rdf\NQuads();
      $serialized = $nquads->serialize($quads);
      
    • Reverse: Parse N-Quads back to JSON-LD:
      $quads = $nquads->parse($serialized);
      $document = JsonLD::fromRdf($quads);
      
  3. Node-Centric API (Experimental):

    • Manipulate graphs programmatically:
      $doc = JsonLD::getDocument($jsonLdString);
      $graph = $doc->getGraph();
      $node = $graph->getNode('http://example.com/node1');
      $node->addPropertyValue('http://example.com/vocab/name', 'Test');
      
  4. HTTP Integration:

    • Load remote JSON-LD directly:
      $remoteJsonLd = JsonLD::expand('https://example.com/data.jsonld');
      

Laravel-Specific Patterns

  1. Service Provider: Bind the processor to Laravel’s container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(\SweetRdf\JsonLD\JsonLD::class, function () {
            return new \SweetRdf\JsonLD\JsonLD();
        });
    }
    
  2. Middleware for API Responses: Automatically expand/compact JSON-LD in API responses:

    // app/Http/Middleware/JsonLdResponse.php
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if ($request->wantsJson() && $response->getContentType() === 'application/ld+json') {
            $expanded = JsonLD::expand($response->getContent());
            $response->setContent(JsonLD::toString($expanded));
        }
        return $response;
    }
    
  3. Eloquent Models: Store JSON-LD as serialized data in a database and hydrate/dehydrate:

    // app/Models/JsonLdModel.php
    protected $casts = [
        'json_ld_data' => JsonLdData::class,
    ];
    
    class JsonLdData implements CastsAttributes
    {
        public function get($model, string $key, $value, array $attributes)
        {
            return JsonLD::expand($value);
        }
    
        public function set($model, string $key, $value, array $attributes)
        {
            return JsonLD::toString($value);
        }
    }
    
  4. API Resources: Use JSON-LD framing to shape API responses:

    // app/Http/Resources/JsonLdResource.php
    public function toArray($request)
    {
        $frame = file_get_contents('frame.jsonld');
        $framed = JsonLD::frame(parent::toArray($request), $frame);
        return $framed;
    }
    

Gotchas and Tips

Pitfalls

  1. HTTP Header Leaks:

    • Issue: Headers from previous HTTP requests may persist (fixed in v1.4.1).
    • Workaround: Clear headers manually if reusing the processor:
      JsonLD::clearHeaders();
      
  2. Deprecated ml/iri:

    • The package replaces ml/iri with sweetrdf/iri (v1.4.0+). Ensure no legacy code relies on the old package.
  3. PHP 8+ Attributes:

    • Some test annotations (e.g., @dataProvider) are updated to PHP 8 attributes (#[DataProvider]). Older PHP versions may throw warnings.
  4. Node-Centric API Limitations:

    • The object-oriented interface (e.g., getDocument()) is experimental. Prefer the static API for production.
  5. Framing Complexity:

    • Deep filtering or aggressive re-embedding in frames can lead to unexpected behavior. Test with the online playground first.
  6. Quad Serialization:

    • toRdf() returns an array of quads. Ensure your RDF library (e.g., sweetrdf/rdf) is compatible:
      $quads = JsonLD::toRdf($jsonLdString);
      // $quads is an array of [subject, predicate, object, graph] arrays.
      

Debugging Tips

  1. Validation: Use the JSON-LD Playground to validate inputs before processing.

  2. Error Handling: Wrap calls in try-catch for malformed JSON-LD:

    try {
        $expanded = JsonLD::expand($jsonLdString);
    } catch (\SweetRdf\JsonLD\Exception\JsonLdError $e) {
        Log::error('JSON-LD Error: ' . $e->getMessage());
        abort(500, 'Invalid JSON-LD');
    }
    
  3. Logging: Enable debug output for complex transformations:

    JsonLD::setDebug(true);
    $expanded = JsonLD::expand($jsonLdString);
    
  4. Performance:

    • For large datasets, cache expanded/compacted results:
      $cacheKey = 'jsonld_expanded_' . md5($jsonLdString);
      $expanded = Cache::remember($cacheKey, now()->addHours(1), function () use ($jsonLdString) {
          return JsonLD::expand($jsonLdString);
      });
      

Extension Points

  1. Custom Contexts: Dynamically merge contexts:

    $context = file_get_contents('base-context.jsonld');
    $customContext = ['@vocab' => 'http://custom/vocab/'];
    $mergedContext = JsonLD::mergeContexts($context, $customContext);
    $compacted = JsonLD::compact($jsonLdString, $mergedContext);
    
  2. Event Listeners: Hook into JSON-LD processing (e.g., log transformations):

    JsonLD::addListener('expand', function ($expanded) {
        Log::debug('Expanded JSON-LD:', $expanded);
    });
    
  3. RDF Vocabulary Extensions: Extend the RDF model by subclassing SweetRdf\Rdf\Graph or SweetRdf\Rdf\Node for domain-specific logic.

  4. Custom Serializers: Implement SweetRdf\Rdf\SerializerInterface for non-N-Quads formats (e.g., Turtle):

    class CustomSerializer implements SerializerInterface
    {
        public function serialize($quads) { /* ... */ }
        public function parse($serialized) { /* ... */ }
    }
    

Configuration Quirks

  1. Default Graph Handling:

    • toRdf() includes a default graph. Explicitly filter it if needed:
      $quads = JsonLD::toRdf($jsonLdString);
      $namedGraphs = array_filter($quads, fn($quad) => $quad[3] !== null);
      
  2. Blank Node Stability:

    • Blank nodes (e.g., _:b1) may change across expansions. Use URIs for stable references.
  3. **Case Sensitivity

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor