public function attachDb($db)
{
if ($this->shouldCollect('db', true)) {
static $profiler, $eventsManager, $queryCollector;
$config = $this->config;
if (!$profiler) {
$profiler = new Profiler();
}
try {
if (!$queryCollector) {
$queryCollector = new QueryCollector($profiler);
if ($config->options->db->get('with_params', false)) {
$queryCollector->setRenderSqlWithParams();
}
if ($config->options->db->backtrace) {
$queryCollector->setFindSource(true);
}
if ($config->options->db->get('show_conn', false)) {
$queryCollector->setShowConnection(true);
}
if ($config->options->db->get('explain', false)) {
$profiler->setExplainQuery(true);
}
$this->addCollector($queryCollector);
}
} catch (\Exception $e) {
$this->addException(new Exception('Cannot add listen to Queries for Phalcon Debugbar: ' . $e->getMessage(), $e->getCode(), $e));
}
if (is_string($db)) {
$db = $this->di[$db];
}
$pdo = $db->getInternalHandler();
$pdo->setAttribute(\PDO::ATTR_ERRMODE, $config->options->db->error_mode);
if (!$eventsManager) {
$eventsManager = $db->getEventsManager();
if (!is_object($eventsManager)) {
$eventsManager = new Manager();
}
$eventsManager->attach('db', function (Event $event, Adapter $db, $params) use($profiler, $queryCollector) {
$profiler->setDb($db);
if ($event->getType() == 'beforeQuery') {
$sql = $db->getRealSQLStatement();
$bindTypes = $db->getSQLBindTypes();
if (stripos(strtr($sql, [' ' => '']), 'SELECTIF(COUNT(*)>0,1,0)FROM`INFORMATION_SCHEMA`.`TABLES`') === false && stripos($sql, 'DESCRIBE') !== 0) {
$profiler->startProfile($sql, $params, $bindTypes);
if ($queryCollector->getFindSource()) {
try {
$source = $queryCollector->findSource();
$profiler->setSource($source);
} catch (\Exception $e) {
}
}
}
}
if ($event->getType() == 'afterQuery') {
$sql = $db->getRealSQLStatement();
if (stripos(strtr($sql, [' ' => '']), 'SELECTIF(COUNT(*)>0,1,0)FROM`INFORMATION_SCHEMA`.`TABLES`') === false && stripos($sql, 'DESCRIBE') !== 0) {
$profiler->stopProfile();
}
}
});
}
$db->setEventsManager($eventsManager);
}
}