|
| 1 | +# PHP JSON Patch |
| 2 | + |
| 3 | +[](https://packagist.org/packages/remorhaz/php-json-patch) |
| 4 | +[](https://packagist.org/packages/remorhaz/php-json-patch) |
| 5 | +[](https://travis-ci.org/remorhaz/php-json-patch) |
| 6 | +[](https://codeclimate.com/github/remorhaz/php-json-patch) |
| 7 | +[](https://codeclimate.com/github/remorhaz/php-json-patch/coverage) |
| 8 | + |
| 9 | +This library implements [RFC6902](https://tools.ietf.org/html/rfc6902)-compliant JSON patch tool. |
| 10 | + |
| 11 | +##Requirements |
| 12 | +* PHP 7.0+ |
| 13 | + |
| 14 | +##Features |
| 15 | +* Supports PHP 7.0 |
| 16 | +* No PHP extensions required |
| 17 | +* Throws SPL exceptions |
| 18 | + |
| 19 | +#License |
| 20 | +PHP JSON Patch is licensed under MIT license. |
| 21 | + |
| 22 | +#Installation |
| 23 | +You will need [composer](https://getcomposer.org) to perform install. |
| 24 | +``` |
| 25 | +composer require remorhaz/php-json-patch |
| 26 | +``` |
| 27 | + |
| 28 | +#Documentation |
| 29 | +## Data accessors |
| 30 | +Patch tool utilizes JSON data accessor interfaces defined in package |
| 31 | +**[remorhaz/php-json-data](https://github.com/remorhaz/php-json-data)**. Read more about them in package documentation. |
| 32 | +There is a ready-to-work implementation in that package that works with native PHP structures (like the ones you get as |
| 33 | +a result of `json_decode` function). You can use `RawSelectableReader` class to bind to patch data and |
| 34 | +`RawSelectableWriter` class to bind to the document that is to be patched. You can also implement your own accessors |
| 35 | +if you need to work with another sort of data (like unparsed JSON text, for example). |
| 36 | + |
| 37 | +## Using patch tool |
| 38 | +To apply JSON Patch to the JSON document you need just 4 simple steps: |
| 39 | + |
| 40 | +1. Create an instance of read-only accessor bound to your patch data. |
| 41 | +2. Create an instance of writabe accessor bound to your document. |
| 42 | +3. Create an object of `\Remorhaz\JSON\Patch\Patch` by calling it's constructor with a document accessor as an argument. |
| 43 | +4. Call its `apply()` method with patch accessor as an argument. |
| 44 | + |
| 45 | +##Example of usage |
| 46 | +```php |
| 47 | +<?php |
| 48 | + |
| 49 | +use \Remorhaz\JSON\Data\RawSelectableReader; |
| 50 | +use \Remorhaz\JSON\Data\RawSelectableWriter; |
| 51 | +use \Remorhaz\JSON\Patch\Patch; |
| 52 | + |
| 53 | +// Setting up document. |
| 54 | +$data = (object) ['a' => (object) ['b' => 'c', 'd' => 'e']; |
| 55 | +$dataWriter = new RawSelectableWriter($data); |
| 56 | + |
| 57 | +// Setting up patch. |
| 58 | +$patchData = [ |
| 59 | + (object) ['op' => 'add', 'path' => '/a/f', 'value' => 'g'], |
| 60 | +]; |
| 61 | +$patchReader = new RawSelectableReader($patchData); |
| 62 | + |
| 63 | +// Applying the patch. |
| 64 | +(new Patch($dataWriter))->apply($patchReader); // $data->a->f property is added and set to 'g' |
0 commit comments