|
| 1 | +<?php |
| 2 | + |
| 3 | +require_once __DIR__.'/vendor/autoload.php'; |
| 4 | + |
| 5 | +use Symfony\Component\Yaml\Yaml; |
| 6 | + |
| 7 | +/** |
| 8 | + * Validate console input |
| 9 | + * |
| 10 | + * Die if input is not valid |
| 11 | + * |
| 12 | + * @param array $argv user inputs |
| 13 | + */ |
| 14 | +function validateInput($argv) |
| 15 | +{ |
| 16 | + if (count($argv) !== 4) { |
| 17 | + echo 'php compare_hashmaps <file1> <file2> <root_node>' . PHP_EOL; |
| 18 | + die(1); |
| 19 | + } |
| 20 | + |
| 21 | + if (!file_exists($argv[1])) { |
| 22 | + echo "Error: " . $argv[1] . " is not a valid file" . PHP_EOL; |
| 23 | + die(1); |
| 24 | + } |
| 25 | + if (!file_exists($argv[2])) { |
| 26 | + echo "Error: " . $argv[2] . " is not a valid file" . PHP_EOL; |
| 27 | + die(1); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * @param string $filepath |
| 33 | + * @param string $rootNode |
| 34 | + * |
| 35 | + * @return array |
| 36 | + * @throws Exception |
| 37 | + */ |
| 38 | +function extractArrayFromFile($filepath, $rootNode) |
| 39 | +{ |
| 40 | + $value = Yaml::parse(file_get_contents($filepath)); |
| 41 | + |
| 42 | + if (!array_key_exists($rootNode, $value)) { |
| 43 | + $showKeys = implode(', ', array_keys($value)); |
| 44 | + throw new \RuntimeException("Expects root node '$rootNode'' in file $filepath, got: $showKeys"); |
| 45 | + } |
| 46 | + |
| 47 | + return $value[$rootNode]; |
| 48 | +} |
| 49 | + |
| 50 | +validateInput($argv); |
| 51 | + |
| 52 | +require 'Util/TextColorWriter.php'; |
| 53 | + |
| 54 | +$filepath1 = $argv[1]; |
| 55 | +$filepath2 = $argv[2]; |
| 56 | +$rootNode = $argv[3]; |
| 57 | + |
| 58 | +$list1 = extractArrayFromFile(realpath($filepath1), $rootNode); |
| 59 | +$list2 = extractArrayFromFile(realpath($filepath2), $rootNode); |
| 60 | + |
| 61 | +$inFile1ButNotInFile2 = []; |
| 62 | +$inFile2ButNotInFile1 = []; |
| 63 | + |
| 64 | +foreach ($list1 as $key => $value) { |
| 65 | + if (!array_key_exists($key, $list2)) { |
| 66 | + $inFile1ButNotInFile2[$key] = $value; |
| 67 | + } |
| 68 | +} |
| 69 | +foreach ($list2 as $key => $value) { |
| 70 | + if (!array_key_exists($key, $list1)) { |
| 71 | + $inFile2ButNotInFile1[$key] = $value; |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | + |
| 76 | +// echo result |
| 77 | +echo TextColorWriter::textColor('Done', TextColorWriter::BASH_PROMPT_GREEN) . PHP_EOL; |
| 78 | +echo TextColorWriter::textColor('Found in file 1 but not in file 2:', TextColorWriter::BASH_PROMPT_GREEN) . PHP_EOL; |
| 79 | + |
| 80 | +foreach ($inFile1ButNotInFile2 as $key => $value) { |
| 81 | + echo ' - ' . $key . PHP_EOL; |
| 82 | +} |
| 83 | + |
| 84 | +echo TextColorWriter::textColor('Found in file 2 but not in file 1:', TextColorWriter::BASH_PROMPT_GREEN) . PHP_EOL; |
| 85 | + |
| 86 | +foreach ($inFile2ButNotInFile1 as $key => $value) { |
| 87 | + echo ' - ' . $key . PHP_EOL; |
| 88 | +} |
0 commit comments