-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathProfilingPlugin.php
96 lines (81 loc) · 2.74 KB
/
ProfilingPlugin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
declare(strict_types=1);
/*
* This file is part of the BazingaGeocoderBundle package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Bazinga\GeocoderBundle\Plugin;
use Geocoder\Collection;
use Geocoder\Exception\Exception;
use Geocoder\Exception\LogicException;
use Geocoder\Plugin\Plugin;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\Query;
use Geocoder\Query\ReverseQuery;
use Http\Promise\Promise;
/**
* @author Tobias Nyholm <[email protected]>
*/
class ProfilingPlugin implements Plugin
{
/**
* @var list<array{query: Query, queryString: string, duration: float, providerName: string, result: mixed, resultCount: int}>
*/
private array $queries = [];
/**
* service id of the provider.
*/
private string $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function handleQuery(Query $query, callable $next, callable $first): Promise
{
$startTime = microtime(true);
return $next($query)->then(function (Collection $result) use ($query, $startTime): Collection {
$duration = (microtime(true) - $startTime) * 1000;
$this->logQuery($query, $duration, $result);
return $result;
}, function (Exception $exception) use ($query, $startTime): void {
$duration = (microtime(true) - $startTime) * 1000;
$this->logQuery($query, $duration, $exception);
throw $exception;
});
}
/**
* @param mixed $result
*/
private function logQuery(Query $query, float $duration, $result = null): void
{
if ($query instanceof GeocodeQuery) {
$queryString = $query->getText();
} elseif ($query instanceof ReverseQuery) {
$queryString = sprintf('(%s, %s)', $query->getCoordinates()->getLongitude(), $query->getCoordinates()->getLatitude());
} else {
throw new LogicException('First parameter to ProfilingProvider::logQuery must be a Query');
}
$this->queries[] = [
'query' => $query,
'queryString' => $queryString,
'duration' => $duration,
'providerName' => $this->getName(),
'result' => $result,
'resultCount' => $result instanceof Collection ? $result->count() : 0,
];
}
/**
* @return list<array{query: Query, queryString: string, duration: float, providerName: string, result: mixed, resultCount: int}>
*/
public function getQueries(): array
{
return $this->queries;
}
public function getName(): string
{
return $this->name;
}
}