PHP code example of victuxbb / jsonpatch

1. Go to this page and download the library: Download victuxbb/jsonpatch 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/ */

    

victuxbb / jsonpatch example snippets

 php
$targetJSON ='{"baz": "qux","foo": "bar"}';
 php
$patchOperations = '[
     { "op": "replace", "path": "/baz", "value": "boo" }
   ]';
 php
$patcher = new Patcher();
$result = $patcher->patch($targetJSON,$patchOperations);
 php
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;

    }