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