VersionPress\Utils\EntityUtils::getDiff PHP Method

getDiff() public static method

Or the $newEntityData might be another full entity, for example in its new state. It doesn't really matter, the algo is always the same: it scans for new keys in $newEntityData and changed values on existing keys and adds those two things to the result. 'vp_id' key is ignored by default. Note: keys may never be "removed" (or marked as removed) in the diff because that will just not ever happen - the SQL UPDATE command is only capable of sending a change, clearing a key value at most but never "removing" it entirely.
public static getDiff ( array $oldEntityData, array $newEntityData ) : array
$oldEntityData array Usually a full entity data in its original state
$newEntityData array Full or partial data of the new entity
return array Key=>value pairs of things that are new or changed in $newEntity (they can never be "removed", that will never happen when capturing SQL UPDATE actions)
    public static function getDiff($oldEntityData, $newEntityData)
    {
        $diff = [];
        foreach ($newEntityData as $key => $value) {
            if (!array_key_exists($key, $oldEntityData) || self::isChanged($oldEntityData[$key], $value)) {
                $diff[$key] = $value;
            }
        }
        return $diff;
    }

Usage Example

 public function save($data)
 {
     $vpid = $data[$this->entityInfo->vpidColumnName];
     if (!$vpid) {
         return null;
     }
     if ($this->entityInfo->usesGeneratedVpids) {
         // to avoid merge conflicts
         unset($data[$this->entityInfo->idColumnName]);
     }
     $data = $this->removeUnwantedColumns($data);
     if (!$this->shouldBeSaved($data)) {
         return null;
     }
     $filename = $this->getEntityFilename($vpid);
     $oldSerializedEntity = "";
     $isExistingEntity = $this->exists($vpid);
     if ($isExistingEntity) {
         $oldSerializedEntity = file_get_contents($filename);
     }
     $oldEntity = $this->deserializeEntity($oldSerializedEntity);
     $diff = EntityUtils::getDiff($oldEntity, $data);
     if (count($diff) > 0) {
         $newEntity = array_merge($oldEntity, $diff);
         $newEntity = array_filter($newEntity, function ($value) {
             return $value !== false;
         });
         FileSystem::mkdir(dirname($this->getEntityFilename($vpid)));
         file_put_contents($filename, $this->serializeEntity($vpid, $newEntity));
         return $this->createChangeInfo($oldEntity, $newEntity, !$isExistingEntity ? 'create' : 'edit');
     } else {
         return null;
     }
 }
All Usage Examples Of VersionPress\Utils\EntityUtils::getDiff