PageRenderTime 56ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/SpotCommandline.php

https://github.com/elstenaar86/spotweb
PHP | 91 lines | 45 code | 9 blank | 37 comment | 15 complexity | 04d9aebbe97c7d753f7881176f55d457 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, MPL-2.0-no-copyleft-exception, 0BSD, Apache-2.0
  1. <?php
  2. class SpotCommandline {
  3. private static $_parsed = null;
  4. private static $_defaults = null;
  5. /*
  6. * $noopt is the list of parameters without value
  7. * $defaults is the list of default values for parameters
  8. *
  9. */
  10. static public function initialize($noopt, $defaults) {
  11. self::$_parsed = self::parseParameters($noopt);
  12. self::$_defaults = $defaults;
  13. } # initialize
  14. /*
  15. * Are we running from the commandline?
  16. */
  17. static public function isCommandline() {
  18. return (!isset($_SERVER['SERVER_PROTOCOL']));
  19. } # isCommandline
  20. /*
  21. * Returns either the value of the function or '1'
  22. * when set
  23. *
  24. * When the parameter is not given, we return the
  25. * default value
  26. */
  27. static public function get($val) {
  28. if (isset(self::$_parsed[$val])) {
  29. return self::$_parsed[$val];
  30. } else {
  31. return self::$_defaults[$val];
  32. } # else
  33. } # get
  34. /**
  35. *
  36. * This code is copied from:
  37. * http://nl.php.net/manual/en/function.getopt.php#83414
  38. *
  39. * Parses $GLOBALS['argv'] for parameters and assigns them to an array.
  40. *
  41. * Supports:
  42. * -e
  43. * -e <value>
  44. * --long-param
  45. * --long-param=<value>
  46. * --long-param <value>
  47. * <value>
  48. *
  49. * @param array $noopt List of parameters without values
  50. */
  51. static private function parseParameters($noopt = array()) {
  52. $result = array();
  53. if (!isset($GLOBALS['argv'])) {
  54. return $result;
  55. } # if
  56. $params = $GLOBALS['argv'];
  57. // could use getopt() here (since PHP 5.3.0), but it doesn't work reliably
  58. reset($params);
  59. while (list($tmp, $p) = each($params)) {
  60. if ($p{0} == '-') {
  61. $pname = substr($p, 1);
  62. $value = true;
  63. if ($pname{0} == '-') {
  64. // long-opt (--<param>)
  65. $pname = substr($pname, 1);
  66. if (strpos($p, '=') !== false) {
  67. // value specified inline (--<param>=<value>)
  68. list($pname, $value) = explode('=', substr($p, 2), 2);
  69. }
  70. }
  71. // check if next parameter is a descriptor or a value
  72. $nextparm = current($params);
  73. if (!in_array($pname, $noopt) && $value === true && $nextparm !== false && $nextparm{0} != '-') list($tmp, $value) = each($params);
  74. $result[$pname] = $value;
  75. } else {
  76. // param doesn't belong to any option
  77. $result[] = $p;
  78. }
  79. }
  80. return $result;
  81. } # parseParameters
  82. } # SpotCommandline