<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Doctrine\DBAL\Query;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;

class TablePrefixingQueryBuilder extends QueryBuilder
{
    private $prefix;

    public function __construct(Connection $connection, string $dbPrefix)
    {
        parent::__construct($connection);

        $this->prefix = $dbPrefix;
    }

    /**
     * @param string $sqlPartName
     * @param mixed $sqlPart
     * @param bool $append
     *
     * @return static
     */
    public function add($sqlPartName, $sqlPart, $append = false): self
    {
        switch ($sqlPartName) {
            case 'from':
                $sqlPart['table'] = $this->prefix . $sqlPart['table'];
                break;
            case 'join':
                assert(is_array($sqlPart));
                $joinAlias = key($sqlPart);
                $sqlPart[$joinAlias]['joinTable'] = $this->prefix . $sqlPart[$joinAlias]['joinTable'];
                break;
            default:
                break;
        }

        return parent::add($sqlPartName, $sqlPart, $append);
    }
}
