PHP code example of bycerfrance / json-fragments

1. Go to this page and download the library: Download bycerfrance/json-fragments library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bycerfrance / json-fragments example snippets


use ByCerfrance\JsonFragments\JsonFragmenter;
use ByCerfrance\JsonFragments\Storage\FlysystemFragmentStorage;
use League\Flysystem\Filesystem;

// $adapter is a configured Flysystem adapter (S3, local, etc.).
$filesystem = new Filesystem($adapter);
$storage = new FlysystemFragmentStorage($filesystem, storagePrefix: 'datasets/weather-station');
$fragmenter = new JsonFragmenter($storage);

$data = [
    'title' => 'Weather observations',
    'unit' => 'celsius',
    'samples' => [
        ['time' => '08:00', 'temperature' => 12.5],
        ['time' => '09:00', 'temperature' => 14.2],
    ],
];
$compressed = $fragmenter->externalize($data, ['/samples']);
// The samples branch becomes: {"$ref":"jsonfragment://<fragment-id>.json"}
// The title and unit remain inline.
// Physical location: datasets/weather-station/<fragment-id>.json

// $mountManager has a configured "results" mount; $resultUuid comes from the application.
$storage = new FlysystemFragmentStorage(
    filesystem: $mountManager,
    referencePrefix: 'jsonfragment://',
    storagePrefix: 'results://' . $resultUuid,
);
$fragmenter = new JsonFragmenter($storage);
$resource = $fragmenter->stream($responseData);
// Consume the resource, then close it (or transfer ownership to a PSR-7 body).

$data = json_decode($encodedJson, associative: false, flags: JSON_THROW_ON_ERROR);

$compressed = $fragmenter->externalize($data, ['/samples']);

// Store each matching test value in its own fragment:
$compressed = $fragmenter->externalizeMatching($data, [
    '/items/*/detail/*/test',
]);

// Alternatively, store each item in its own fragment, keeping the items container inline:
$compressed = $fragmenter->externalizeMatching($data, ['/items/*']);

// Build a lightweight JSON document containing references:
$prepared = $fragmenter->externalize($data, ['/samples']);
$encodedJson = json_encode($fragmenter->dehydrate($prepared), JSON_THROW_ON_ERROR);

// Reopen the document using the same filesystem context:
$decoded = json_decode($encodedJson, associative: false, flags: JSON_THROW_ON_ERROR);
$hydrated = $fragmenter->hydrate($decoded);

$title = $hydrated->title;                  // No storage read.
$samples = $hydrated->samples;              // JsonFragment; still no read.
$values = $samples->resolve();              // Reads once and caches the content.
$completeJson = json_encode($hydrated, JSON_THROW_ON_ERROR); // Complete content.

// Serialize the lightweight representation again, without reading any fragments:
$encodedJson = json_encode($fragmenter->dehydrate($hydrated), JSON_THROW_ON_ERROR);

// $decoded contains the lightweight document and its references.
// $destination is an already-open writable stream, such as an export file.
$stream = $fragmenter->stream($decoded);

try {
    stream_copy_to_stream($stream, $destination);
} finally {
    fclose($stream);
}

/** @return resource */
public function readStream(JsonReference $reference);

// $streamFactory implements Psr\Http\Message\StreamFactoryInterface (PSR-17).
$resource = $fragmenter->stream($decoded);

try {
    $body = $streamFactory->createStreamFromResource($resource);
} catch (\Throwable $exception) {
    fclose($resource);
    throw $exception;
}

$response = $response
    ->withHeader('Content-Type', 'application/json')
    ->withBody($body);

use ByCerfrance\JsonFragments\JsonReference;

$reference = new JsonReference(
    ref: 'https://example.org/schema.json',
    properties: ['description' => 'Dataset schema'],
);

$reference->getRef();        // Original identifier.
$reference->getScheme();     // "https"; null for a relative reference.
$reference->getProperties(); // Sibling properties, preserved on serialization.

$store = new FlysystemFragmentStorage(
    $filesystem,
    referencePrefix: 'custom://fragments/',
);

foreach ($fragmenter->references($data) as $pointer => $reference) {
    $identifier = $reference->getRef();
    $scheme = $reference->getScheme();
    $supported = $store->supports($reference);
}

$fragmenter->validateReferences($responseData); // Existence checks only; no fragment is opened.
$resource = $fragmenter->stream($responseData);

public function exists(JsonReference $reference): bool;

public function supports(JsonReference $reference): bool;
public function resolve(JsonReference $reference): mixed;

public function store(mixed $value): JsonReference;