remorhaz/php-json-patch

JSON Patch (RFC-6902) PHP implementation

v0.6.1 2024-02-21 21:30 UTC

This package is auto-updated.

Last update: 2024-11-21 23:01:21 UTC


README

Latest Stable Version Build Scrutinizer Code Quality codecov Mutation testing badgeTotal Downloads License

This library implements RFC6902-compliant JSON patch tool.

Requirements

Installation

You will need composer to perform install.

composer require remorhaz/php-json-patch

Documentation

Accessing JSON document

You can create accessible JSON document either from encoded JSON string or from decoded JSON data using corresponding node value factory:

use Remorhaz\JSON\Data\Value\EncodedJson;
use Remorhaz\JSON\Data\Value\DecodedJson;

// Creating document from JSON-encoded string:
$encodedValueFactory = EncodedJson\NodeValueFactory::create();
$encodedJson = '{"a":1}';
$document1 = $encodedValueFactory->createValue($encodedJson);

// Creating document from decoded JSON data:
$decodedValueFactory = DecodedJson\NodeValueFactory::create();
$decodedJson = (object) ['a' => 1];
$document2 = $decodedValueFactory->createValue($decodedJson);

Creating and processing query

You should use query factory to create query from JSON Patch document. Then you should use processor to apply that query:

<?php
use Remorhaz\JSON\Data\Value\EncodedJson;
use Remorhaz\JSON\Patch\Processor\Processor;
use Remorhaz\JSON\Patch\Query\QueryFactory;

$encodedValueFactory = EncodedJson\NodeValueFactory::create();
$queryFactory = QueryFactory::create();
$processor = Processor::create();

$patch = $encodedValueFactory->createValue('[{"op":"remove","path":"/0"}]');
$query = $queryFactory->createQuery($patch);

$document = $encodedValueFactory->createValue('[1,2]');
$result = $processor->apply($query, $document);

var_dump($result->encode()); // string: '[2]'
var_dump($result->decode()); // array: [2]

Note that result can be exported either to JSON-encoded string or to raw PHP value.

License

PHP JSON Patch is licensed under MIT license.