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.

81 lines
1.8 KiB

2 years ago
  1. <?php namespace WpsMcloud;
  2. use WpsMcloud\Exceptions\LoggerException;
  3. class Logger
  4. {
  5. const LOG_TYPE_HTML = 'html';
  6. const LOG_TYPE_ERROR_LOG = 'error_log';
  7. const LOG_TYPE_BOTH = 'both';
  8. private static array $logTypes = [
  9. self::LOG_TYPE_HTML,
  10. self::LOG_TYPE_ERROR_LOG,
  11. self::LOG_TYPE_BOTH,
  12. ];
  13. private string $logType;
  14. /**
  15. * @param string $logType
  16. * @throws LoggerException
  17. */
  18. public function __construct(string $logType)
  19. {
  20. $this->validateLogType($logType);
  21. $this->logType = $logType;
  22. }
  23. /**
  24. * @param string $logType
  25. * @throws LoggerException
  26. */
  27. private function validateLogType(string $logType): void
  28. {
  29. if (!in_array($logType, self::$logTypes)) {
  30. throw new LoggerException('Log type wrong: ' . $logType);
  31. }
  32. }
  33. public function log(string $message, bool $newLineAfter = true): void
  34. {
  35. switch ($this->logType) {
  36. case self::LOG_TYPE_HTML:
  37. $this->outputToDefaultStream($message, $newLineAfter);
  38. break;
  39. case self::LOG_TYPE_ERROR_LOG:
  40. $this->outputToPhpErrorLog($message);
  41. break;
  42. case self::LOG_TYPE_BOTH:
  43. $this->outputToDefaultStream($message, $newLineAfter);
  44. $this->outputToPhpErrorLog($message);
  45. break;
  46. }
  47. }
  48. private function outputToDefaultStream(string $message, bool $newLineAfter): void
  49. {
  50. echo $message;
  51. if ($newLineAfter) {
  52. echo PHP_EOL;
  53. }
  54. }
  55. private function outputToPhpErrorLog(string $message): void
  56. {
  57. error_log($message);
  58. }
  59. public function openPreformating()
  60. {
  61. echo '<pre>';
  62. }
  63. public function closePreformating()
  64. {
  65. echo '</pre>';
  66. }
  67. }