Skip to content

Commit

Permalink
Refactoring for code reuse
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jan 10, 2013
1 parent 2db5305 commit e0ac0e7
Showing 1 changed file with 23 additions and 44 deletions.
67 changes: 23 additions & 44 deletions lib/Cake/Model/Datasource/Database/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -292,60 +292,20 @@ public function join($tables = null, $types = [], $overwrite = false) {
}

public function where($conditions = null, $types = [], $overwrite = false) {
$where = $this->_parts['where'] ?: $this->newExpr();
if ($conditions === null) {
return $where;
}

if (is_callable($conditions)) {
$this->_parts['where'] = $conditions($where, $this);
return $this;
}

if ($overwrite) {
$this->_parts['where'] = $this->newExpr()->add($conditions, $types);
} else {
$where->add($conditions, $types);
$this->_parts['where'] = $this->newExpr();
}

$this->_parts['where'] = $where;
$this->_dirty = true;
$this->_conjugate('where', $conditions, 'AND', $types);
return $this;
}

public function andWhere($conditions, $types = []) {
$where = $this->_parts['where'] ?: $this->newExpr();

if (is_callable($conditions)) {
$conditions = $conditions($this->newExpr(), $this);
}

if ($where->type() === 'AND') {
$where->add($conditions, $types);
} else {
$where = $this->newExpr()->add([$conditions, $where], $types);
}

$this->_parts['where'] = $where;
$this->_dirty = true;
$this->_conjugate('where', $conditions, 'AND', $types);
return $this;
}

public function orWhere($conditions, $types = []) {
$where = $this->_parts['where'] ?: $this->newExpr()->type('OR');

if (is_callable($conditions)) {
$conditions = $conditions($this->newExpr(), $this);
}

if ($where->type() === 'OR') {
$where->add($conditions, $types);
} else {
$where = $this->newExpr()->type('OR')->add([$conditions, $where], $types);
}

$this->_parts['where'] = $where;
$this->_dirty = true;
$this->_conjugate('where', $conditions, 'OR', $types);
return $this;
}

Expand Down Expand Up @@ -437,6 +397,25 @@ public function getIterator() {
return $this->_iterator;
}

protected function _conjugate($part, $append, $conjunction, $types) {
$expression = $this->_parts[$part] ?: $this->newExpr();

if (is_callable($append)) {
$append = $append($this->newExpr(), $this);
}

if ($expression->type() === $conjunction) {
$expression->add($append, $types);
} else {
$expression = $this->newExpr()
->type($conjunction)
->add([$append, $expression], $types);
}

$this->_parts[$part] = $expression;
$this->_dirty = true;
}

/**
* Returns string representation of this query (complete SQL statement)
*
Expand Down

0 comments on commit e0ac0e7

Please sign in to comment.