mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-09-25 13:59:08 +02:00
PHP7 FluentInterface
This commit is contained in:
@@ -2,79 +2,51 @@
|
||||
|
||||
namespace DesignPatterns\Structural\FluentInterface;
|
||||
|
||||
/**
|
||||
* class SQL.
|
||||
*/
|
||||
class Sql
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $fields = array();
|
||||
private $fields = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $from = array();
|
||||
private $from = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $where = array();
|
||||
private $where = [];
|
||||
|
||||
/**
|
||||
* adds select fields.
|
||||
*
|
||||
* @param array $fields
|
||||
*
|
||||
* @return SQL
|
||||
*/
|
||||
public function select(array $fields = array())
|
||||
public function select(array $fields): Sql
|
||||
{
|
||||
$this->fields = $fields;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* adds a FROM clause.
|
||||
*
|
||||
* @param string $table
|
||||
* @param string $alias
|
||||
*
|
||||
* @return SQL
|
||||
*/
|
||||
public function from($table, $alias)
|
||||
public function from(string $table, string $alias): Sql
|
||||
{
|
||||
$this->from[] = $table.' AS '.$alias;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* adds a WHERE condition.
|
||||
*
|
||||
* @param string $condition
|
||||
*
|
||||
* @return SQL
|
||||
*/
|
||||
public function where($condition)
|
||||
public function where(string $condition): Sql
|
||||
{
|
||||
$this->where[] = $condition;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the query, just an example of building a query,
|
||||
* no check on consistency.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getQuery()
|
||||
public function __toString(): string
|
||||
{
|
||||
return 'SELECT '.implode(',', $this->fields)
|
||||
.' FROM '.implode(',', $this->from)
|
||||
.' WHERE '.implode(' AND ', $this->where);
|
||||
return sprintf(
|
||||
'SELECT %s FROM %s WHERE %s',
|
||||
join(', ', $this->fields),
|
||||
join(', ', $this->from),
|
||||
join(' AND ', $this->where)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user