|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * This file is part of CodeIgniter 4 framework. |
| 5 | + * |
| 6 | + * (c) CodeIgniter Foundation <admin@codeigniter.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view |
| 9 | + * the LICENSE file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace CodeIgniter\Commands\Translation\LocalizationFinder; |
| 13 | + |
| 14 | +class ArrayHelper |
| 15 | +{ |
| 16 | + /** |
| 17 | + * Compare recursive two associative arrays and return new array (difference) |
| 18 | + * Returns keys that exist in $original but not in $compareWith |
| 19 | + */ |
| 20 | + public static function recursiveDiff(array $original, array $compareWith): array |
| 21 | + { |
| 22 | + $difference = []; |
| 23 | + |
| 24 | + if ([] === $original) { |
| 25 | + return []; |
| 26 | + } |
| 27 | + |
| 28 | + if ([] === $compareWith) { |
| 29 | + return $original; |
| 30 | + } |
| 31 | + |
| 32 | + foreach ($original as $originalKey => $originalValue) { |
| 33 | + if ([] === $originalValue) { |
| 34 | + continue; |
| 35 | + } |
| 36 | + |
| 37 | + if (is_array($originalValue)) { |
| 38 | + $diffArrays = []; |
| 39 | + |
| 40 | + if (isset($compareWith[$originalKey]) && is_array($compareWith[$originalKey])) { |
| 41 | + $diffArrays = self::recursiveDiff($originalValue, $compareWith[$originalKey]); |
| 42 | + } else { |
| 43 | + $difference[$originalKey] = $originalValue; |
| 44 | + } |
| 45 | + |
| 46 | + if ([] !== $diffArrays) { |
| 47 | + $difference[$originalKey] = $diffArrays; |
| 48 | + } |
| 49 | + } elseif (is_string($originalValue) && ! array_key_exists($originalKey, $compareWith)) { |
| 50 | + $difference[$originalKey] = $originalValue; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return $difference; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Count all keys (with nested keys) |
| 59 | + */ |
| 60 | + public static function recursiveCount(array $array, int $counter = 0): int |
| 61 | + { |
| 62 | + foreach ($array as $value) { |
| 63 | + if (is_array($value)) { |
| 64 | + $counter = self::recursiveCount($value, $counter); |
| 65 | + } |
| 66 | + |
| 67 | + $counter++; |
| 68 | + } |
| 69 | + |
| 70 | + return $counter; |
| 71 | + } |
| 72 | +} |
0 commit comments