<?php
/**
 * Copyright (C) 2023  Jaap Jansma (jaap.jansma@civicoop.org)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

namespace Civi\DataProcessor\DataFlow\SqlDataFlow;

use Civi\DataProcessor\DataFlow\SqlTableDataFlow;

class SqlTableDataFlowWithSqlFilter extends SqlTableDataFlow {

  /** @var null|string */
  protected $filter_sql = null;

  public function __construct(string $table, string $table_alias, string $filter_sql=null) {
    parent::__construct($table, $table_alias);
    $this->filter_sql = $filter_sql;
  }

  /**
   * Returns a subquery, applying any custom filter_sql, identified as table_alias.
   *
   * @return string
   */
  public function getTableStatement(): string {
    // If table has been saved prior to filter_sql being defined, the blank
    // value in filter_sql will be of type DataSpecification. Fall back to "1"
    // to avoid problems.
    if ($this->filter_sql && !is_object($this->filter_sql) && is_string($this->filter_sql)) {
      return " (SELECT * FROM `$this->table` WHERE $this->filter_sql)  AS  `$this->table_alias` ";
    }
    return "`$this->table` `$this->table_alias`";
  }

}
