php-jsonpatch/php-jsonpatch

Implementation of JSON Patch (http://tools.ietf.org/html/rfc6902)

Installs: 10 725

Dependents: 2

Stars: 33

Watchers: 5

Forks: 4

Language: PHP

v1.2.0 2015-05-20 23:08 UTC

README

Build Status Version PHP Version

This is an implementation of JSON Patch written in PHP.

Dependencies (managed via Composer)

JSON Pointer for PHP by Raphael Stolt.

Installation via Composer

$ composer require php-jsonpatch/php-jsonpatch:1.2.*

Usage

Now you can use JSON Patch for PHP via the available Composer autoload file.

Patch operations are defined in JSON and bundled in an array. Available JSON Patch operations are add, remove, replace, move, copy, and test; if their mandatory properties are not set a Rs\Json\Patch\InvalidOperationException will be thrown.

<?php require_once 'vendor/autoload.php';

use Rs\Json\Patch;
use Rs\Json\Patch\InvalidPatchDocumentJsonException;
use Rs\Json\Patch\InvalidTargetDocumentJsonException;
use Rs\Json\Patch\InvalidOperationException;

try {
    $targetDocument = '{"a":{"b":["c","d","e"]}}';

    $patchDocument = '[
        {"op":"add", "path":"/a/d", "value":["a","b"]}, // {"a":{"b":["c","d","e"],"d":["a","b"]}}
        {"op":"test", "path":"/a/d/-", "value":"b"}, // previous target document
        {"op":"remove", "path":"/a/d/-"}, // {"a":{"b":["c","d","e"],"d":["a"]}}
        {"op":"test", "path":"/a/d/-", "value":"a"}, // previous target document
        {"op":"add", "path":"/a/d/-", "value":"b"}, // {"a":{"b":["c","d","e"],"d":["a","b"]}}
        {"op":"test", "path":"/a/d", "value":["a","b"]}, // previous target document
        {"op":"move", "path":"/a/c", "from":"/a/d"}, // {"a":{"b":["c","d","e"],"c":["a","b"]}}
        {"op":"test", "path":"/a/c", "value":["a","b"]}, // previous target document
        {"op":"copy", "path":"/a/e", "from":"/a/c"}, //   {"a":{"b":["c","d","e"],"c":["a","b"],"e":["a","b"]}}
        {"op":"test", "path":"/a/e", "value":["a","b"]}, // previous target document
        {"op":"replace", "path":"/a/e", "value":["a"]}, // {"a":{"b":["c","d","e"],"c":["a","b"],"e":["a"]}}
        {"op":"test", "path":"/a/e", "value":["a"]} // previous target document
    ]';

    $patch = new Patch($targetDocument, $patchDocument);
    $patchedDocument = $patch->apply(); // {"a":{"b":["c","d","e"],"c":["a","b"],"e":["a"]}}
} catch (InvalidPatchDocumentJsonException $e) {
    // Will be thrown when using invalid JSON in a patch document
} catch (InvalidTargetDocumentJsonException $e) {
    // Will be thrown when using invalid JSON in a target document
} catch (InvalidOperationException $e) {
    // Will be thrown when using an invalid JSON Pointer operation (i.e. missing property)
}

For some more usage examples of JSON Patch operations have a look at the integration tests located under tests/integration/*.

Testing

$ composer test

License

This library is licensed under the MIT License. Please see License file for more information.