CLIOptionsHandler.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /* vim: set shiftwidth=2 expandtab softtabstop=2: */
  3. namespace Boris;
  4. /**
  5. * Processes available command line flags.
  6. */
  7. class CLIOptionsHandler {
  8. /**
  9. * Accept the REPL object and perform any setup necessary from the CLI flags.
  10. *
  11. * @param Boris $boris
  12. */
  13. public function handle($boris) {
  14. $args = getopt('hvr:', array('help', 'version', 'require:'));
  15. foreach ($args as $option => $value) {
  16. switch ($option) {
  17. /*
  18. * Sets files to load at startup, may be used multiple times,
  19. * i.e: boris -r test.php,foo/bar.php -r ba/foo.php --require hey.php
  20. */
  21. case 'r':
  22. case 'require':
  23. $this->_handleRequire($boris, $value);
  24. break;
  25. /*
  26. * Show Usage info
  27. */
  28. case 'h':
  29. case 'help':
  30. $this->_handleUsageInfo();
  31. break;
  32. /*
  33. * Show version
  34. */
  35. case 'v':
  36. case 'version':
  37. $this->_handleVersion();
  38. break;
  39. }
  40. }
  41. }
  42. // -- Private Methods
  43. private function _handleRequire($boris, $paths) {
  44. $require = array_reduce(
  45. (array) $paths,
  46. function($acc, $v) { return array_merge($acc, explode(',', $v)); },
  47. array()
  48. );
  49. $boris->onStart(function($worker, $scope) use($require) {
  50. foreach($require as $path) {
  51. require $path;
  52. }
  53. $worker->setLocal(get_defined_vars());
  54. });
  55. }
  56. private function _handleUsageInfo() {
  57. echo <<<USAGE
  58. Usage: boris [options]
  59. boris is a tiny REPL for PHP
  60. Options:
  61. -h, --help show this help message and exit
  62. -r, --require a comma-separated list of files to require on startup
  63. -v, --version show Boris version
  64. USAGE;
  65. exit(0);
  66. }
  67. private function _handleVersion() {
  68. printf("Boris %s\n", Boris::VERSION);
  69. exit(0);
  70. }
  71. }