victuxbb / jsonpatch
Implementation of JSON Patch (http://tools.ietf.org/html/rfc6902)
Installs: 21 660
Dependents: 0
Suggesters: 0
Security: 0
Stars: 5
Watchers: 5
Forks: 1
Open Issues: 0
Requires
- php: >=5.3.3
Requires (Dev)
- phpunit/phpunit: 4.3.*
This package is not auto-updated.
Last update: 2024-11-05 03:36:37 UTC
README
Implementation of JSON Patch (http://tools.ietf.org/html/rfc6902) in PHP
Installation
Require victuxbb/jsonpatch
into your composer.json
file:
{ "require": { "victuxbb/jsonpatch": "@stable" } }
or inside your root project directory
$ composer require victuxbb/jsonpatch @stable
Documentation
With a target JSON like this:
$targetJSON ='{"baz": "qux","foo": "bar"}';
and a variable with a JSON string operations:
$patchOperations = '[ { "op": "replace", "path": "/baz", "value": "boo" } ]';
create a instance of Patcher and use the "patch" method to get the json result:
$patcher = new Patcher(); $result = $patcher->patch($targetJSON,$patchOperations);
$result will contain:
{"baz":"boo","foo":"bar"}
A typical use case with FOSRestBundle and JMSSerializer:
public function patchUserAction(Request $request,User $user) { $json = $request->getContent(); $jps = $this->get('json_patch_service'); //symfony service that loads Patcher.php $serializer = $this->get("jms_serializer"); $serializerGroup = array('view'); $sc = SerializationContext::create(); $sc->setGroups($serializerGroup); $jsonUser = $serializer->serialize($user,'json',$sc); //Generating the json target of object that we want to update $jsonUser = $jps->patch($jsonUser,$json); //json result with the changes applied of the json operations $dc = DeserializationContext::create(); $dc->setAttribute('target',$user); //Restore the doctrine entity object with deserialization and targeting the object with DeserializationContext $serializer->deserialize($jsonUser,'Groupalia\BizApiBundle\Entity\User','json',$dc); $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush(); $response = new Response(); $response->setStatusCode(200); return $response; }
Thanks to
*https://github.com/javadegava
*http://williamdurand.fr/2014/02/14/please-do-not-patch-like-an-idiot/