MergeHostsFile.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace FD3;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Input\InputArgument;
  6. use Symfony\Component\Console\Input\InputOption;
  7. use Symfony\Component\Console\Output\OutputInterface;
  8. class MergeHostsFile extends Command
  9. {
  10. protected function configure()
  11. {
  12. $this
  13. ->setName('merge:hostsfile')
  14. ->setDescription('Merge (or remove) two hostfiles to /etc/hosts.')
  15. ->setHelp('This command allows you to a new installation...')
  16. ->addArgument('file', InputArgument::REQUIRED, 'The file to use.')
  17. ->addOption('dest', null, InputOption::VALUE_REQUIRED, 'The /etc/hosts file where to write', "/etc/hosts")
  18. ->addOption('ref', null, InputOption::VALUE_REQUIRED, 'The reference to add as a comment to simplify the remove', "handled by fd3")
  19. ->addOption('del', 'd', InputOption::VALUE_NONE, 'Remove the merged values based on the ref parameter');
  20. }
  21. protected function execute(InputInterface $input, OutputInterface $output)
  22. {
  23. $file = $input->getArgument('file');
  24. $dest = $input->getOption("dest");
  25. $id = $input->getOption("ref");
  26. $del = $input->getOption("del");
  27. $dest_content = explode("\n", file_get_contents($dest));
  28. $orig_content = explode("\n", file_get_contents($file));
  29. foreach ($dest_content as $k => $spect) {
  30. if (strpos($spect, $id) !== false) {
  31. unset($dest_content[$k]);
  32. }
  33. }
  34. foreach ($orig_content as $k => $spect) {
  35. $spect = trim($spect);
  36. preg_match("|[^\s]*|", $spect, $match);
  37. if (isset($match[0])) {
  38. try {
  39. $ip = \IP::create($match[0]);
  40. $orig_content[$k] = $spect . "\t#$id";
  41. } catch (\InvalidArgumentException $e) {
  42. }
  43. }
  44. }
  45. $content = "";
  46. foreach ($dest_content as $line) {
  47. $content .= $line . "\n";
  48. }
  49. if (!$del) {
  50. foreach ($orig_content as $line) {
  51. $content .= $line . "\n";
  52. }
  53. }
  54. file_put_contents($dest, $content);
  55. }
  56. }