|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Gitonomy\Bundle\GitBundle\DataCollector; |
| 4 | + |
| 5 | +use Symfony\Component\HttpFoundation\Request; |
| 6 | +use Symfony\Component\HttpFoundation\Response; |
| 7 | + |
| 8 | +use Symfony\Component\HttpKernel\DataCollector\DataCollector; |
| 9 | + |
| 10 | +use Monolog\Handler\TestHandler; |
| 11 | +use Monolog\Logger; |
| 12 | + |
| 13 | +use Gitonomy\Git\Repository; |
| 14 | + |
| 15 | +class GitDataCollector extends DataCollector |
| 16 | +{ |
| 17 | + protected $handlers = array(); |
| 18 | + |
| 19 | + public function collect(Request $request, Response $response, \Exception $exception = null) |
| 20 | + { |
| 21 | + $this->data = array(); |
| 22 | + |
| 23 | + foreach ($this->handlers as $name => $handler) { |
| 24 | + $this->data[$name] = $handler->getRecords(); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + public function getName() |
| 29 | + { |
| 30 | + return 'git'; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Injects Logger inside the repository. |
| 35 | + */ |
| 36 | + public function addRepository(Repository $repository) |
| 37 | + { |
| 38 | + if (null !== $repository->getLogger()) { |
| 39 | + throw new \RuntimeException('A logger is already injected in repository.'); |
| 40 | + } |
| 41 | + |
| 42 | + $name = $repository->getGitDir(); |
| 43 | + $logger = new Logger($name); |
| 44 | + $handler = new TestHandler(); |
| 45 | + $logger->pushHandler($handler); |
| 46 | + |
| 47 | + $this->handlers[$name] = $handler; |
| 48 | + |
| 49 | + $repository->setLogger($logger); |
| 50 | + } |
| 51 | + |
| 52 | + public function getCount($name = null) |
| 53 | + { |
| 54 | + $count = 0; |
| 55 | + |
| 56 | + // How to count run commands |
| 57 | + $callback = function ($entry) { |
| 58 | + return preg_match('/^run command/', $entry['message']); |
| 59 | + }; |
| 60 | + |
| 61 | + if ($name) { |
| 62 | + return array_sum(array_map($callback, $this->data[$name])); |
| 63 | + } |
| 64 | + |
| 65 | + foreach ($this->data as $channel) { |
| 66 | + $count += array_sum(array_map($callback, $channel)); |
| 67 | + } |
| 68 | + |
| 69 | + return $count; |
| 70 | + } |
| 71 | + |
| 72 | + public function getDuration($name = null) |
| 73 | + { |
| 74 | + $count = 0; |
| 75 | + |
| 76 | + // How to count duration |
| 77 | + $callback = function ($entry) { |
| 78 | + if (preg_match('/duration: ([\d.]+)ms$/', $entry['message'], $vars)) { |
| 79 | + return (float) $vars[1]; |
| 80 | + } |
| 81 | + |
| 82 | + return 0; |
| 83 | + }; |
| 84 | + |
| 85 | + if ($name) { |
| 86 | + return array_sum(array_map($callback, $this->data[$name])); |
| 87 | + } |
| 88 | + |
| 89 | + foreach ($this->data as $channel) { |
| 90 | + $count += array_sum(array_map($callback, $channel)); |
| 91 | + } |
| 92 | + |
| 93 | + return $count; |
| 94 | + } |
| 95 | + |
| 96 | + public function getData() |
| 97 | + { |
| 98 | + return null === $this->data ? array() : $this->data; |
| 99 | + } |
| 100 | +} |
0 commit comments