|
| 1 | +<?php |
| 2 | + |
| 3 | + |
| 4 | +/** |
| 5 | + * Validate console input |
| 6 | + * |
| 7 | + * Die if input is not valid |
| 8 | + * |
| 9 | + * @param array $argv user inputs |
| 10 | + */ |
| 11 | +function validateInput($argv) |
| 12 | +{ |
| 13 | + if (count($argv) !== 4) { |
| 14 | + echo 'php remove_from_file <file1> <file2> <output>' . PHP_EOL; |
| 15 | + die(1); |
| 16 | + } |
| 17 | + |
| 18 | + if (!file_exists($argv[1])) { |
| 19 | + echo "Error: " . $argv[1] . " is not a valid file" . PHP_EOL; |
| 20 | + die(1); |
| 21 | + } |
| 22 | + if (!file_exists($argv[2])) { |
| 23 | + echo "Error: " . $argv[2] . " is not a valid file" . PHP_EOL; |
| 24 | + die(1); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * @param string $filepath |
| 30 | + * |
| 31 | + * @return array blacklist is in keys |
| 32 | + * @throws Exception |
| 33 | + */ |
| 34 | +function computeBlackListFromFile($filepath) |
| 35 | +{ |
| 36 | + $handle = fopen($filepath, "r"); |
| 37 | + |
| 38 | + if (false === $handle) { |
| 39 | + throw new \Exception("Could not open file $filepath"); |
| 40 | + } |
| 41 | + |
| 42 | + $blackList = array(); |
| 43 | + |
| 44 | + while (($line = fgets($handle)) !== false) { |
| 45 | + $blackList[trim($line)] = true; |
| 46 | + } |
| 47 | + |
| 48 | + fclose($handle); |
| 49 | + |
| 50 | + return $blackList; |
| 51 | +} |
| 52 | + |
| 53 | +validateInput($argv); |
| 54 | + |
| 55 | +require 'Util/TextColorWriter.php'; |
| 56 | + |
| 57 | +$filepath1 = $argv[1]; |
| 58 | +$filepath2 = $argv[2]; |
| 59 | +$outputFilepath = $argv[3]; |
| 60 | + |
| 61 | +$blackList = computeBlackListFromFile($filepath2); |
| 62 | + |
| 63 | +$fileHandle1 = fopen($filepath1, "r"); |
| 64 | +$outputFile = fopen($outputFilepath, 'w'); |
| 65 | + |
| 66 | +if (false === $fileHandle1) { |
| 67 | + throw new \Exception("Could not open file $fileHandle1"); |
| 68 | +} |
| 69 | +if (false === $outputFile) { |
| 70 | + throw new \Exception("Could not write file $outputFile"); |
| 71 | +} |
| 72 | + |
| 73 | +$i = 0; |
| 74 | +$removed = 0; |
| 75 | +while (($line = fgets($fileHandle1)) !== false) { |
| 76 | + |
| 77 | + $isNotInBlacklist = (false === isset($blackList[trim($line)])); |
| 78 | + |
| 79 | + if ($isNotInBlacklist) { |
| 80 | + fwrite($outputFile, $line); |
| 81 | + } else { |
| 82 | + $removed++; |
| 83 | + } |
| 84 | + |
| 85 | + $i++; |
| 86 | +} |
| 87 | + |
| 88 | +fclose($fileHandle1); |
| 89 | +fclose($outputFile); |
| 90 | + |
| 91 | +// echo result |
| 92 | +echo TextColorWriter::textColor('Done', TextColorWriter::BASH_PROMPT_GREEN) . PHP_EOL; |
| 93 | +echo TextColorWriter::textColor("Processed : $i lines", TextColorWriter::BASH_PROMPT_CYAN) . PHP_EOL; |
| 94 | +echo TextColorWriter::textColor("Removed : $removed lines", TextColorWriter::BASH_PROMPT_CYAN) . PHP_EOL; |
0 commit comments