You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.3 KiB

10 years ago
  1. <?php namespace Majestic\App;
  2. /**
  3. * @copyright NetMonsters <team@netmonsters.ru>
  4. * @link http://netmonsters.ru
  5. * @package Majestic
  6. * @subpackage App
  7. * @since 27.06.12
  8. *
  9. */
  10. /**
  11. * @desc CliController (run cli_class, end profiler)
  12. * @author Aleksandr Demidov
  13. */
  14. class CliController
  15. {
  16. /**
  17. * @var CliController
  18. */
  19. protected static $instance;
  20. protected $error_stream;
  21. protected function __construct()
  22. {
  23. ErrorHandler::init();
  24. $this->error_stream = Config::get('ErrorStream', 'php://stderr');
  25. }
  26. /**
  27. * Refuse cloning
  28. * @codeCoverageIgnoreStart
  29. */
  30. private function __clone()
  31. {
  32. }
  33. /**
  34. * @codeCoverageIgnoreEnd
  35. */
  36. /**
  37. * @static
  38. * @return CliController
  39. */
  40. public static function getInstance()
  41. {
  42. if (!isset(self::$instance)) {
  43. self::$instance = new static();
  44. }
  45. return self::$instance;
  46. }
  47. /**
  48. * @param iCli|string $cli
  49. * @throws ErrorException|GeneralException
  50. */
  51. public function execute($cli)
  52. {
  53. try {
  54. $this->run($cli);
  55. }
  56. catch (Exception $e) {
  57. $this->exception($e);
  58. }
  59. }
  60. protected function run($cli)
  61. {
  62. if (is_string($cli)) {
  63. if (!class_exists($cli)) {
  64. throw new GeneralException('Action class "' . $cli . '" not found.');
  65. }
  66. $cli = new $cli;
  67. }
  68. if (!in_array('iCli', class_implements($cli))) {
  69. throw new ErrorException('Runner "' . get_class($cli) . '" need implement of "iCli" interface.');
  70. }
  71. $cli->run();
  72. if (Config::get('PROFILER')) {
  73. $profile = Profiler::getInstance()->getCli();
  74. if (Config::get('LOGGING')) {
  75. Logger::getInstance()->log($profile);
  76. } else {
  77. echo $profile;
  78. }
  79. }
  80. }
  81. protected function exception($e)
  82. {
  83. $code = $e->getCode();
  84. if ($e instanceof ErrorException) {
  85. $code = $e->getSeverity();
  86. }
  87. file_put_contents($this->error_stream, PHP_EOL . 'Error ' . '#' . $code . ': ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
  88. file_put_contents($this->error_stream, PHP_EOL . 'Stack trace: ' . PHP_EOL . $e->getTraceAsString() . PHP_EOL, FILE_APPEND);
  89. }
  90. }