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
namespace Omeka\Db\Logging;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Logging\SQLLogger;
use PDO;
use SplFileObject;

class FileSqlLogger implements SQLLogger
{
    /**
     * List of PDO and Doctrine built-in types
     */
    protected $types = [
        PDO::PARAM_BOOL => 'PARAM_BOOL',
        PDO::PARAM_NULL => 'PARAM_NULL',
        PDO::PARAM_INT => 'PARAM_INT',
        PDO::PARAM_STR => 'PARAM_STR',
        PDO::PARAM_LOB => 'PARAM_LOB',
        Connection::PARAM_INT_ARRAY => 'PARAM_INT_ARRAY',
        Connection::PARAM_STR_ARRAY => 'PARAM_STR_ARRAY',
    ];

    /**
     * @var SplFileObject
     */
    protected $file;

    /**
     * @var float
     */
    protected $startTime;

    /**
     * @var string
     */
    protected $entry;

    /**
     * Set the file object.
     *
     * @param string $path
     */
    public function __construct($path)
    {
        $this->file = new SplFileObject($path, 'a');
    }

    /**
     * Log SQL to file.
     *
     * @param string $sql
     * @param null|array $params
     * @param null|array $types
     */
    public function startQuery($sql, array $params = null, array $types = null)
    {
        $entry = $sql . PHP_EOL;

        if ($params) {
            foreach ($params as $index => $param) {
                $type = isset($types[$index]) ? $this->getType($types[$index]) : 'default';
                $entry .= sprintf('  %s: (%s) %s%s',
                    $index,
                    $type,
                    json_encode($param, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
                    PHP_EOL
                );
            }
        }

        $this->entry = $entry;
        $this->startTime = microtime(true);
    }

    public function stopQuery()
    {
        $duration = microtime(true) - $this->startTime;
        $entry = sprintf('%s (%0.3F)', date('c', $this->startTime), $duration) . PHP_EOL
            . $this->entry
            . PHP_EOL;
        $this->file->fwrite($entry);

        $this->startTime = null;
        $this->entry = null;
    }

    protected function getType($type)
    {
        if (array_key_exists($type, $this->types)) {
            return $this->types[$type];
        }
        return $type;
    }
}