<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Db\SQLBuilders;

class DeleteQueryBuilder extends \QueryBuilder
{
  
  public $table;

  
  public $where = '';

  protected function getSQLString()
  {
    assert(!is_null($this->table));
    if (is_null($this->where) || trim($this->where) === '') {
      return ''; 
    }

    return 'DELETE FROM ' . $this->table . ' WHERE ' . $this->where;
  }

  public function deleteFrom(string $table)
  {
    $this->table = $table;

    return $this;
  }

  public function from(string $table)
  {
    return $this->deleteFrom($table);
  }

  
  public function where($sql)
  {
    $this->where = $sql . ' ';

    return $this;
  }

  
  public function addToWhere($sql)
  {
    if (trim($sql) != '') {
      $this->where .= $sql . ' ';
    }

    return $this;
  }

  
  public function addOperatorToWhere($sql, $op)
  {
    if (trim($sql) != '') {
      $trimmedwhere = trim($this->where);
      if ($trimmedwhere != '' && !\StringOperations::endsWith($trimmedwhere, '(')) {
        $this->addToWhere($op);
      }

      $this->addToWhere($sql);
    }

    return $this;
  }

  
  public function and($sql)
  {
    return $this->addOperatorToWhere($sql, 'AND');
  }
}