|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Syonix\LogViewer; |
| 4 | + |
| 5 | +use DateTime; |
| 6 | + |
| 7 | +class LogApiHelper |
| 8 | +{ |
| 9 | + private LogManager $manager; |
| 10 | + |
| 11 | + public function __construct(LogManager $manager) |
| 12 | + { |
| 13 | + $this->manager = $manager; |
| 14 | + } |
| 15 | + |
| 16 | + public function getLogs($urlPrefix = ''): array |
| 17 | + { |
| 18 | + $result = []; |
| 19 | + foreach ($this->manager->getCollections() as $collection) { |
| 20 | + $row = [ |
| 21 | + 'name' => $collection->getName(), |
| 22 | + 'slug' => $collection->getSlug(), |
| 23 | + ]; |
| 24 | + |
| 25 | + foreach ($collection->getLogs() as $log) |
| 26 | + $row['logs'][] = [ |
| 27 | + 'name' => $log->getName(), |
| 28 | + 'slug' => $log->getSlug(), |
| 29 | + ]; |
| 30 | + |
| 31 | + $result[] = $row; |
| 32 | + } |
| 33 | + |
| 34 | + return $result; |
| 35 | + } |
| 36 | + |
| 37 | + public function getLog($collection, $log, $limit, $offset = 0, array $filter = [], $urlPrefix = ''): array |
| 38 | + { |
| 39 | + $collection = $this->manager->getLogCollection($collection); |
| 40 | + $log = $this->manager->loadLog($collection->getLog($log)); |
| 41 | + $totalLines = $log->countLines($filter); |
| 42 | + |
| 43 | + $prevOffset = max($offset - $limit, 0); |
| 44 | + $nextOffset = $offset + $limit; |
| 45 | + |
| 46 | + $id = $log->getIdentifier(); |
| 47 | + $prev = $offset > 0 ? "$urlPrefix/$id?limit=$limit&offset=$prevOffset" : null; |
| 48 | + $next = $nextOffset < $totalLines ? "$urlPrefix/$id?limit=$limit&offset=$nextOffset" : null; |
| 49 | + |
| 50 | + foreach ($filter as $k => $f) { |
| 51 | + if ($f === null) |
| 52 | + continue; |
| 53 | + |
| 54 | + if ($prev !== null) |
| 55 | + $prev .= "&$k=$f"; |
| 56 | + |
| 57 | + if ($next !== null) |
| 58 | + $next .= "&$k=$f"; |
| 59 | + } |
| 60 | + |
| 61 | + // TODO: Use proper URL Builder |
| 62 | + |
| 63 | + $lines = $log->getLines($limit, $offset, $filter); |
| 64 | + |
| 65 | + foreach ($lines as &$line) |
| 66 | + $line['date'] = $line['date'] instanceof DateTime ? $line['date']->format('c') : null; // TODO: Improve |
| 67 | + |
| 68 | + return [ |
| 69 | + 'name' => $log->getName(), |
| 70 | + 'slug' => $log->getSlug(), |
| 71 | + 'collection' => [ |
| 72 | + 'name' => $collection->getName(), |
| 73 | + 'slug' => $collection->getSlug(), |
| 74 | + ], |
| 75 | + 'lines' => $lines, |
| 76 | + 'total_lines' => $totalLines, |
| 77 | + 'offset' => $offset, |
| 78 | + 'limit' => $limit, |
| 79 | + 'loggers' => $log->getLoggers()->toArray(), |
| 80 | + 'prev' => $prev, |
| 81 | + 'next' => $next, |
| 82 | + ]; |
| 83 | + } |
| 84 | +} |
0 commit comments