db = $db; $this->tableName = $tableName; $this->columnMap = $columnMap; if (! empty($separator)) { $this->separator = $separator; } if (! $this->hasFormatter()) { $this->setFormatter(new DbFormatter()); } } /** * Remove reference to database adapter * * @return void */ public function shutdown() { $this->db = null; } /** * Write a message to the log. * * @param array $event event data * @return void * @throws Exception\RuntimeException */ protected function doWrite(array $event) { if (null === $this->db) { throw new Exception\RuntimeException('Database adapter is null'); } $event = $this->formatter->format($event); // Transform the event array into fields if (null === $this->columnMap) { $dataToInsert = $this->eventIntoColumn($event); } else { $dataToInsert = $this->mapEventIntoColumn($event, $this->columnMap); } $statement = $this->db->query($this->prepareInsert($dataToInsert)); $statement->execute($dataToInsert); } /** * Prepare the INSERT SQL statement * * @param array $fields * @return string */ protected function prepareInsert(array $fields) { $keys = array_keys($fields); return 'INSERT INTO ' . $this->db->platform->quoteIdentifier($this->tableName) . ' (' . implode(",", array_map([$this->db->platform, 'quoteIdentifier'], $keys)) . ') VALUES (' . implode(",", array_map([$this->db->driver, 'formatParameterName'], $keys)) . ')'; } /** * Map event into column using the $columnMap array * * @param array $event * @param array $columnMap * @return array */ protected function mapEventIntoColumn(array $event, ?array $columnMap = null) { if (empty($event)) { return []; } $data = []; foreach ($event as $name => $value) { if (is_array($value)) { foreach ($value as $key => $subvalue) { if (isset($columnMap[$name][$key])) { if (is_scalar($subvalue)) { $data[$columnMap[$name][$key]] = $subvalue; continue; } $data[$columnMap[$name][$key]] = var_export($subvalue, true); } } } elseif (isset($columnMap[$name])) { $data[$columnMap[$name]] = $value; } } return $data; } /** * Transform event into column for the db table * * @param array $event * @return array */ protected function eventIntoColumn(array $event) { if (empty($event)) { return []; } $data = []; foreach ($event as $name => $value) { if (is_array($value)) { foreach ($value as $key => $subvalue) { if (is_scalar($subvalue)) { $data[$name . $this->separator . $key] = $subvalue; continue; } $data[$name . $this->separator . $key] = var_export($subvalue, true); } } else { $data[$name] = $value; } } return $data; } }