<?php
/*
 * Copyright (c) 2023. RTM Business
 */

namespace WordpressModels\ORM;

use Doctrine\DBAL\Driver\AbstractSQLiteDriver;
use Doctrine\DBAL\Driver\PDO\Connection;
use ReflectionClass;

class WpdbSQLiteDriver extends AbstractSQLiteDriver
{
    /**
     * Get the `wpdb::$dhb` property and use it as the MySQL Connection constructor parameter.
     * @param array $params
     * @return Connection
     * @throws \Doctrine\DBAL\Exception
     */
    public function connect(array $params): Connection
    {
        global $wpdb;

        if (!$wpdb instanceof \WP_SQLite_DB) {
            throw new \RuntimeException('Only official WordPress SQLite integration is supported. See https://github.com/WordPress/sqlite-database-integration for more information.');
        }

        $reflectionClass = new ReflectionClass(\WP_SQLite_DB::class);
        $property = $reflectionClass->getProperty('dbh');
        /** @var \WP_SQLite_Translator $dbh */
        $dbh = $property->getValue($wpdb);

        return new Connection($dbh->get_pdo());
    }
}
