|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace Tyrellsys\CakePHPLog; |
| 5 | + |
| 6 | +use Cake\Datasource\EntityInterface; |
| 7 | +use Cake\Error\Debugger; |
| 8 | +use JsonSerializable; |
| 9 | + |
| 10 | +class Formatter |
| 11 | +{ |
| 12 | + /** |
| 13 | + * @param string|array $data data |
| 14 | + * @return string |
| 15 | + */ |
| 16 | + public static function getMessage($data): string |
| 17 | + { |
| 18 | + $isArray = is_array($data); |
| 19 | + |
| 20 | + $data = (array)$data; |
| 21 | + |
| 22 | + $result = []; |
| 23 | + foreach ($data as $key => $record) { |
| 24 | + if (is_string($record)) { |
| 25 | + $result[$key] = $record; |
| 26 | + continue; |
| 27 | + } |
| 28 | + |
| 29 | + $isObject = is_object($record); |
| 30 | + |
| 31 | + if ($isObject && $record instanceof EntityInterface) { |
| 32 | + $result[$key] = json_encode($record, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); |
| 33 | + continue; |
| 34 | + } |
| 35 | + |
| 36 | + if ($isObject && method_exists($record, '__toString')) { |
| 37 | + $result[$key] = (string)$record; |
| 38 | + continue; |
| 39 | + } |
| 40 | + |
| 41 | + if ($isObject && $record instanceof JsonSerializable) { |
| 42 | + $result[$key] = json_encode($record, JSON_UNESCAPED_UNICODE); |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + $result[$key] = print_r($record, true); |
| 47 | + } |
| 48 | + |
| 49 | + $message = static::_prefix(); |
| 50 | + if ($isArray) { |
| 51 | + $message .= print_r($result, true); |
| 52 | + } else { |
| 53 | + $message .= current($result); |
| 54 | + } |
| 55 | + $message .= static::_suffix(); |
| 56 | + |
| 57 | + return $message; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * |
| 62 | + * @return string |
| 63 | + */ |
| 64 | + protected static function _prefix(): string |
| 65 | + { |
| 66 | + $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); |
| 67 | + $found = null; |
| 68 | + $dirname = dirname(__DIR__); |
| 69 | + $length = strlen($dirname); |
| 70 | + $before = null; |
| 71 | + foreach ($traces as $trace) { |
| 72 | + if (substr($trace['file'], 0, $length) !== $dirname) { |
| 73 | + $found = preg_match('#^' . preg_quote(APP) . '#', $trace['file']) ? $trace : $before; |
| 74 | + break; |
| 75 | + } |
| 76 | + $before = $trace; |
| 77 | + } |
| 78 | + |
| 79 | + // [hostname]:path/to/caller_filename:[caller line no](pid): |
| 80 | + return '[' . php_uname('n') . ']:' . |
| 81 | + Debugger::trimPath($found['file']) . |
| 82 | + '(' . $found['line'] . ')' . |
| 83 | + '[' . getmypid() . ']: '; |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * |
| 88 | + * @return string |
| 89 | + */ |
| 90 | + protected static function _suffix(): string |
| 91 | + { |
| 92 | + return ""; |
| 93 | + } |
| 94 | +} |
0 commit comments