PHP code example of xp-forge / json-patch

1. Go to this page and download the library: Download xp-forge/json-patch 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/ */

    

xp-forge / json-patch example snippets


use text\json\patch\{Changes, TestOperation, AddOperation};

// You can create changes via maps...
$changes= new Changes(
  ['op' => 'test', 'path' => '/best', 'value' => 'Choco Liebniz'],
  ['op' => 'add', 'path' => '/biscuits/1', 'value' => ['name' => 'Ginger Nut']]
);

// ...or by using Operation instances
$changes= new Changes(
  new TestOperation('/best', 'Choco Liebniz'),
  new AddOperation('/biscuits/1', ['name' => 'Ginger Nut'])
);

// If you have a JSON patch document, use the spread operator
$patch= [
  ['op' => 'test', 'path' => '/best', 'value' => 'Choco Liebniz'],
  ['op' => 'add', 'path' => '/biscuits/1', 'value' => ['name' => 'Ginger Nut']]
];
$changes= new Changes(...$patch);

$document= [
  'best' => 'Choco Liebniz',
  'biscuits' => [
    ['name' => 'Digestive'],
    ['name' => 'Choco Liebniz']
  ]
];

$changed= $changes->apply($document);

// $changed->successful() := true
// $changed->value() := [
//  'best' => 'Choco Liebniz',
//  'biscuits' => [
//    ['name' => 'Digestive'],
//    ['name' => 'Ginger Nut'],
//    ['name' => 'Choco Liebniz']
//  ]
//];

use text\json\patch\Pointer;

$document= [
  'biscuits' => [
    ['name' => 'Digestive'],
    ['name' => 'Choco Liebniz']
  ]
];

$pointer= new Pointer('/biscuits/1');

// $pointer->exists() := true
// $pointer->value() := ['name' => 'Ginger Nut'];

// This will return an text.json.patch.Applied instance. Use its isError() 
// method to discover whether an error occurred.
$result= $pointer->modify('Ginger Nut');

// You can chain calls using the then() method. Closures passed to it will
// only be invoked if applying the operation succeeds, otherwise an Error
// will be returned.
$result= $pointer->remove()->then(function() use($pointer) {
  return $pointer->add('Choco Liebniz');
});