33namespace Appstract \HostsFile ;
44
55use Exception ;
6+ use Illuminate \Support \Collection ;
67
78class Processor
89{
@@ -17,9 +18,8 @@ class Processor
1718 protected $ bakPath ;
1819
1920 /**
20- * @var array
2121 */
22- protected $ lines = [] ;
22+ protected $ lines ;
2323
2424 /**
2525 * Hosts constructor.
@@ -45,6 +45,8 @@ public function __construct($filePath = null)
4545 $ this ->filePath = realpath ($ filePath );
4646 $ this ->bakPath = realpath ($ filePath ).'.bak ' ;
4747
48+ $ this ->lines = new Collection ();
49+
4850 $ this ->readFile ();
4951 }
5052
@@ -55,11 +57,11 @@ public function __construct($filePath = null)
5557 */
5658 public function getLines ()
5759 {
58- return $ this ->lines ;
60+ return $ this ->lines -> all () ;
5961 }
6062
6163 /**
62- * Add a line.
64+ * Adds a line without checking if it already exists .
6365 *
6466 * @param $ip
6567 * @param $domain
@@ -70,11 +72,27 @@ public function getLines()
7072 */
7173 public function addLine ($ ip , $ domain , $ aliases = '' )
7274 {
73- $ this ->lines [ $ domain] = [ 'ip ' => $ ip , 'aliases ' => $ aliases] ;
75+ $ this ->lines -> push ([ ' domain ' => trim ( $ domain ), 'ip ' => trim ( $ ip) , 'aliases ' => trim ( $ aliases)]) ;
7476
7577 return $ this ;
7678 }
7779
80+ /**
81+ * Removes old value and adds new line
82+ *
83+ * @param $ip
84+ * @param $domain
85+ * @param string $aliases
86+ *
87+ * @return Processor
88+ */
89+ public function set ($ ip , $ domain , $ aliases = '' )
90+ {
91+ $ this ->removeLine ($ domain );
92+
93+ return $ this ->addLine ($ ip , $ domain , $ aliases );
94+ }
95+
7896 /**
7997 * @param $domain
8098 *
@@ -87,7 +105,9 @@ public function removeLine($domain)
87105 throw new Exception (sprintf ("'%s', is not a valid domain " , $ domain ));
88106 }
89107
90- unset($ this ->lines [$ domain ]);
108+ $ this ->lines = $ this ->lines ->reject (function ($ item ) use ($ domain ) {
109+ return $ item ['domain ' ] == $ domain ;
110+ });
91111
92112 return $ this ;
93113 }
@@ -177,8 +197,8 @@ protected function writeFile($filePath)
177197
178198 $ file = fopen ($ filePath , 'w ' );
179199
180- foreach ($ this ->lines as $ domain => $ attributes ) {
181- fwrite ($ file , $ attributes ['ip ' ]."\t\t" .$ domain .' ' .$ attributes ['aliases ' ]." \r\n" );
200+ foreach ($ this ->getLines () as $ line ) {
201+ fwrite ($ file , $ line ['ip ' ]."\t\t" .$ line [ ' domain ' ] .' ' .$ line ['aliases ' ]." \r\n" );
182202 }
183203
184204 fclose ($ file );
0 commit comments