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
;
12 class Expression
implements ExpressionInterface
17 const PLACEHOLDER
= '?';
22 protected $expression = '';
27 protected $parameters = array();
32 protected $types = array();
35 * @param string $expression
36 * @param string|array $parameters
39 public function __construct($expression = '', $parameters = null, array $types = array())
42 $this->setExpression($expression);
45 $this->setParameters($parameters);
48 $this->setTypes($types);
55 * @throws Exception\InvalidArgumentException
57 public function setExpression($expression)
59 if (!is_string($expression) ||
$expression == '') {
60 throw new Exception\
InvalidArgumentException('Supplied expression must be a string.');
62 $this->expression
= $expression;
69 public function getExpression()
71 return $this->expression
;
77 * @throws Exception\InvalidArgumentException
79 public function setParameters($parameters)
81 if (!is_scalar($parameters) && !is_array($parameters)) {
82 throw new Exception\
InvalidArgumentException('Expression parameters must be a scalar or array.');
84 $this->parameters
= $parameters;
91 public function getParameters()
93 return $this->parameters
;
100 public function setTypes(array $types)
102 $this->types
= $types;
109 public function getTypes()
116 * @throws Exception\RuntimeException
118 public function getExpressionData()
120 $parameters = (is_scalar($this->parameters
)) ?
array($this->parameters
) : $this->parameters
;
123 $parametersCount = count($parameters);
125 if ($parametersCount == 0 && strpos($this->expression
, self
::PLACEHOLDER
) !== false) {
126 // if there are no parameters, but there is a placeholder
127 $parametersCount = substr_count($this->expression
, self
::PLACEHOLDER
);
128 $parameters = array_fill(0, $parametersCount, null);
131 for ($i = 0; $i < $parametersCount; $i++
) {
132 $types[$i] = (isset($this->types
[$i]) && ($this->types
[$i] == self
::TYPE_IDENTIFIER ||
$this->types
[$i] == self
::TYPE_LITERAL
))
133 ?
$this->types
[$i] : self
::TYPE_VALUE
;
136 // assign locally, escaping % signs
137 $expression = str_replace('%', '%%', $this->expression
);
139 if ($parametersCount > 0) {
141 $expression = str_replace(self
::PLACEHOLDER
, '%s', $expression, $count);
142 if ($count !== $parametersCount) {
143 throw new Exception\
RuntimeException('The number of replacements in the expression does not match the number of parameters');