ArrayUtils.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Utils;
  4. class ArrayUtils
  5. {
  6. /**
  7. * Returns an array containing changes between the first array the keys/values from an array
  8. * which are absent or different from $initialData
  9. *
  10. * If recursive is true, when values are arrays, they'll get processed too to only keep changes. Else,
  11. * the whole value will be added to the changes if there is at least one difference between the former and the latter.
  12. *
  13. * @param mixed[] $initialArray
  14. * @param mixed[] $newArray
  15. * @param bool $recursive
  16. * @param callable|null $callback An optional callback method to test the equality between to values. The callback shall
  17. * accept two parameters (the values) and return true if the values are equals.
  18. * @return mixed[]
  19. */
  20. public function getChanges(array $initialArray, array $newArray, bool $recursive = false, ?callable $callback = null): array
  21. {
  22. $changes = [];
  23. foreach ($newArray as $field => $value) {
  24. if (!array_key_exists($field, $initialArray)) {
  25. $changes[$field] = $value;
  26. }
  27. elseif ($recursive && is_array($initialArray[$field]) && is_array($value)) {
  28. $newVal = $this->getChanges($initialArray[$field], $value, $recursive, $callback);
  29. if (!empty($newVal)) {
  30. $changes[$field] = $newVal;
  31. }
  32. }
  33. elseif ($callback === null && $value !== $initialArray[$field]) {
  34. $changes[$field] = $value;
  35. }
  36. elseif ($callback !== null && !$callback($value, $initialArray[$field])) {
  37. $changes[$field] = $value;
  38. }
  39. }
  40. return $changes;
  41. }
  42. /**
  43. * If the given $key is set in the array and if the corresponding value is not null,
  44. * cast this value and returns it. Else, returns null.
  45. *
  46. * Ex:
  47. *
  48. * $array = ['a' => '123']
  49. *
  50. * ArrayUtils::getAndCast($array, 'a', 'int') // => returns `123` as an integer
  51. * ArrayUtils::getAndCast($array, 'b', 'int') // => returns `null`
  52. *
  53. * @param mixed[] $array
  54. * @param string $key
  55. * @param string $type
  56. * @return mixed
  57. */
  58. public static function getAndCast(array $array, mixed $key, string $type): mixed
  59. {
  60. $value = $array[$key] ?? null;
  61. if ($value !== null) {
  62. settype($value, $type);
  63. }
  64. return $value;
  65. }
  66. }