How to compare two nodes programmatically ?
Get the diff of nodes programmatically, when saving or updating a node to know the difference ?
Example:
function mymodule_entity_update($entity, $type) {
if ($type == 'user' || $type == 'node') {
if (!empty($entity->nid)) {
$entity_old = node_load($entity->nid);
}
else {
$entity_old = user_load($entity->uid);
}
$dif = _mymodule_entity_compare($entity, $entity_old);
}
}
function _mymodule_entity_compare($entity_new, $entity_old) {
$old = (array) $entity_old;
$new = (array) $entity_new;
$dif = array();
$count = 0;
foreach ($new as $key => $val) {
if (isset($old[$key]) && ($key === 'title' || strstr($key, 'field_'))) {
$field_new = $new[$key];
$field_old= $old[$key];
$field_dif = $field_new;
_mymodule_getfielddiffs($field_new, $field_old, $field_dif);
if($field_dif){
$dif[$key]=$field_dif;
}
}
}
return $dif;
}
function _mymodule_getfielddiffs($field_new, $field_old, &$field_dif) {
if (is_array($field_new)) {
foreach ($field_new as $key => $value) {
if (isset($field_dif[$key])) {
if (!_mymodule_getfielddiffs($field_new[$key], $field_old[$key], $field_dif[$key])) {
unset($field_dif[$key]);
}
}
}
if(!count($field_dif)){
return FALSE;
}
return TRUE;
}
else {
if ($field_new == $field_old) {
return FALSE;//No Diff
}
else {
$field_dif = $field_old; // Save old value in to Diff Table (so save)
return TRUE; // Diff
}
}
}
Comments