helpers.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. use Carbon\Carbon;
  3. use Illuminate\Database\Eloquent\Model;
  4. function formatExcelDate(int $timestamp)
  5. {
  6. $diff = intval($timestamp);
  7. $today=new Carbon('1900-01-01');
  8. $day = $today->addDays($diff-2);
  9. return $day->toDateString();
  10. }
  11. function diff($array1,$array2,string $identification,array $mapping,bool $intactDetached = false):array
  12. {
  13. $changes = [
  14. 'attached' => [], 'detached' => [], 'updated' => [],
  15. ];
  16. $map = [];
  17. foreach ($array2 as $item){
  18. if (is_array($item))$map[$item[$identification]] = $item;
  19. else $map[$item->$identification] = json_decode($item,true);
  20. }
  21. foreach ($array1 as $item){
  22. /** @var \stdClass|array|Model $item */
  23. if (!is_array($item) && !is_subclass_of($item,Model::class))$item = (array)$item;
  24. if (!isset($map[$item[$mapping[$identification]]])){
  25. $obj = [];
  26. foreach ($mapping as $column2=>$column1)$obj[$column2] = $item[$column1];
  27. $changes['attached'][] = $obj;continue;
  28. }
  29. $sign = false;
  30. $obj = [];
  31. foreach ($mapping as $column2=>$column1){
  32. $obj[$column2] = $item[$column1];
  33. if ($map[$item[$mapping[$identification]]][$column2] != $item[$column1])$sign = true;
  34. }
  35. if ($sign)$changes['updated'][] = $obj;
  36. unset($map[$item[$mapping[$identification]]]);
  37. }
  38. if ($map){
  39. if ($intactDetached){
  40. foreach ($map as $item){
  41. $obj = [];
  42. foreach ($mapping as $column2=>$column1)$obj[$column2] = $item[$column2];
  43. $changes['detached'][] = $obj;
  44. }
  45. }else $changes['detached'][] = array_keys($map);
  46. }
  47. return $changes;
  48. }