3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Db\Sql\Predicate
;
14 class PredicateSet
implements PredicateInterface
, Countable
16 const COMBINED_BY_AND
= 'AND';
19 const COMBINED_BY_OR
= 'OR';
22 protected $defaultCombination = self
::COMBINED_BY_AND
;
23 protected $predicates = array();
28 * @param null|array $predicates
29 * @param string $defaultCombination
31 public function __construct(array $predicates = null, $defaultCombination = self
::COMBINED_BY_AND
)
33 $this->defaultCombination
= $defaultCombination;
35 foreach ($predicates as $predicate) {
36 $this->addPredicate($predicate);
42 * Add predicate to set
44 * @param PredicateInterface $predicate
45 * @param string $combination
46 * @return PredicateSet
48 public function addPredicate(PredicateInterface
$predicate, $combination = null)
50 if ($combination === null ||
!in_array($combination, array(self
::OP_AND
, self
::OP_OR
))) {
51 $combination = $this->defaultCombination
;
54 if ($combination == self
::OP_OR
) {
55 $this->orPredicate($predicate);
59 $this->andPredicate($predicate);
64 * Return the predicates
66 * @return PredicateInterface[]
68 public function getPredicates()
70 return $this->predicates
;
74 * Add predicate using OR operator
76 * @param PredicateInterface $predicate
77 * @return PredicateSet
79 public function orPredicate(PredicateInterface
$predicate)
81 $this->predicates
[] = array(self
::OP_OR
, $predicate);
86 * Add predicate using AND operator
88 * @param PredicateInterface $predicate
89 * @return PredicateSet
91 public function andPredicate(PredicateInterface
$predicate)
93 $this->predicates
[] = array(self
::OP_AND
, $predicate);
98 * Get predicate parts for where statement
102 public function getExpressionData()
105 for ($i = 0, $count = count($this->predicates
); $i < $count; $i++
) {
107 /** @var $predicate PredicateInterface */
108 $predicate = $this->predicates
[$i][1];
110 if ($predicate instanceof PredicateSet
) {
114 $parts = array_merge($parts, $predicate->getExpressionData());
116 if ($predicate instanceof PredicateSet
) {
120 if (isset($this->predicates
[$i+
1])) {
121 $parts[] = sprintf(' %s ', $this->predicates
[$i+
1][0]);
128 * Get count of attached predicates
132 public function count()
134 return count($this->predicates
);