3 namespace Drupal\webprofiler\Profiler;
5 use Drupal\Core\Database\Connection;
6 use Symfony\Component\HttpKernel\Profiler\Profile;
7 use Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface;
10 * Implements a profiler storage using the DBTNG query api.
12 class DatabaseProfilerStorage implements ProfilerStorageInterface {
15 * The database connection.
17 * @var \Drupal\Core\Database\Connection
22 * Constructs a new DatabaseProfilerStorage instance.
24 * @param \Drupal\Core\Database\Connection $database
25 * The database connection.
27 function __construct(Connection $database) {
28 $this->database = $database;
34 public function find($ip, $url, $limit, $method, $start = NULL, $end = NULL) {
35 $select = $this->database->select('webprofiler', 'wp', ['fetch' => \PDO::FETCH_ASSOC]);
37 if (NULL === $start) {
45 if ($ip = preg_replace('/[^\d\.]/', '', $ip)) {
46 $select->condition('ip', '%' . $this->database->escapeLike($ip) . '%', 'LIKE');
50 $select->condition('url', '%' . $this->database->escapeLike(addcslashes($url, '%_\\')) . '%', 'LIKE');
54 $select->condition('method', $method);
58 $select->condition('time', $start, '>=');
62 $select->condition('time', $end, '<=');
65 $select->fields('wp', [
74 $select->orderBy('time', 'DESC');
75 $select->range(0, $limit);
76 return $select->execute()
77 ->fetchAllAssoc('token');
83 public function read($token) {
84 $record = $this->database->select('webprofiler', 'w')
86 ->condition('token', $token)
89 if (isset($record->data)) {
90 return $this->createProfileFromData($token, $record);
97 public function write(Profile $profile) {
99 'token' => $profile->getToken(),
100 'parent' => $profile->getParentToken(),
101 'data' => base64_encode(serialize($profile->getCollectors())),
102 'ip' => $profile->getIp(),
103 'method' => $profile->getMethod(),
104 'url' => $profile->getUrl(),
105 'time' => $profile->getTime(),
106 'created_at' => time(),
107 'status_code' => $profile->getStatusCode(),
111 $query = $this->database->select('webprofiler', 'w')
112 ->fields('w', ['token']);
113 $query->condition('token', $profile->getToken());
114 $count = $query->countQuery()->execute()->fetchAssoc();
116 if ($count['expression']) {
117 $this->database->update('webprofiler')
119 ->condition('token', $profile->getToken())
123 $this->database->insert('webprofiler')->fields($args)->execute();
127 } catch (\Exception $e) {
137 public function purge() {
138 $this->database->truncate('webprofiler')->execute();
142 * @param string $token
147 private function createProfileFromData($token, $data) {
148 $profile = new Profile($token);
149 $profile->setIp($data->ip);
150 $profile->setMethod($data->method);
151 $profile->setUrl($data->url);
152 $profile->setTime($data->time);
153 $profile->setCollectors(unserialize(base64_decode($data->data)));
154 $profile->setStatusCode($data->status_code);