pastebin

Paste Search Dynamic
Recent pastes
DiffGenerator
  1. <?php
  2.  
  3. // your code goes here
  4. class DiffGenerator
  5. {
  6.     /*
  7.      * @param stdClass $incoming
  8.      * @param stdClass|null $outgoing
  9.      * @return array|null
  10.      */
  11.     public function diff(stdClass $incoming, ?stdClass $outgoing): ?array
  12.     {
  13.         if ($outgoing === null) {
  14.             return null;
  15.         }
  16.  
  17.         return $this->objectDiff($incoming, $outgoing);
  18.     }
  19.  
  20.     /**
  21.      * @param stdClass $obj1
  22.      * @param stdClass $obj2
  23.      * @return array
  24.      */
  25.     private function objectDiff(stdClass $obj1, stdClass $obj2):array
  26.     {
  27.         $a1 = (array)$obj1;
  28.         $a2 = (array)$obj2;
  29.         return $this->arrayDiff($a1, $a2);
  30.     }
  31.  
  32.     /**
  33.      * @param array $a1
  34.      * @param array $a2
  35.      * @return array
  36.      */
  37.     private function arrayDiff(array $a1, array $a2):array
  38.     {
  39.         $r = [];
  40.         foreach ($a1 as $k => $v) {
  41.             if (array_key_exists($k, $a2)) {
  42.                 if ($v instanceof stdClass) {
  43.                     $rad = $this->objectDiff($v, $a2[$k]);
  44.                     if (count($rad)) { $r[$k] = $rad; }
  45.                 }else if (is_array($v)){
  46.                     $rad = $this->arrayDiff($v, $a2[$k]);
  47.                     if (count($rad)) { $r[$k] = $rad; }
  48.                     // required to avoid rounding errors due to the
  49.                     // conversion from string representation to double
  50.                 } else if (is_float($v)){
  51.                     if (abs($v - $a2[$k]) > 0.000000000001) {
  52.                         $r[$k] = array($v, $a2[$k]);
  53.                     }
  54.                 } else {
  55.                     if ($v != $a2[$k]) {
  56.                         $r[$k] = array($v, $a2[$k]);
  57.                     }
  58.                 }
  59.             } else {
  60.                 $r[$k] = array($v, null);
  61.             }
  62.         }
  63.         return $r;
  64.     }
  65. }
  66.  
  67. $compare = new DiffGenerator();
  68. $incoming = (object) array('entry_type' => 'AB');
  69. $outgoing = (object) array('entry_type' => 'F');
  70. $diff = $compare->diff($incoming, $outgoing);
  71.  
  72. echo json_encode($diff);
  73. ?>
Parsed in 0.077 seconds