* @package Mammut\DB\Sql */ class Cases extends \Mammut\StrictObject implements iExpression { protected $expression = ''; protected $matches = array(); public function __construct($expression){ if ($expression) $this->setExpression($expression); if ($parameters) $this->setParameters($parameters); if ($types) $this->setTypes($types); } public function setExpression($expression) { if (!is_string($expression) || $expression == '') throw new \InvalidArgumentException('Supplied expression must be a string.'); $this->expression = $expression; return $this; } public function getExpression() { return $this->expression; } /** * @return iExpression */ public function setTypes(array $matches) { $this->matches = $matches; return $this; } /** * @return array */ public function getTypes() { return $this->matches; } /** * @return array */ public function getSql(iDialect $dialect) { $parameters = (is_scalar($this->parameters)) ? array($this->parameters) : $this->parameters; $types = array(); $parametersCount = count($parameters); if ($parametersCount == 0 && strpos($this->expression, self::PLACEHOLDER) !== false) { // if there are no parameters, but there is a placeholder $parametersCount = substr_count($this->expression, self::PLACEHOLDER); $parameters = array_fill(0, $parametersCount, null); } for ($i = 0; $i < $parametersCount; $i++) { $types[$i] = (isset($this->types[$i]) && ($this->types[$i] == self::TYPE_IDENTIFIER || $this->types[$i] == self::TYPE_LITERAL)) ? $this->types[$i] : self::TYPE_VALUE; } // assign locally, escaping % signs $expression = str_replace('%', '%%', $this->expression); if ($parametersCount > 0) { $count = 0; $expression = str_replace(self::PLACEHOLDER, '%s', $expression, $count); if ($count !== $parametersCount) { throw new \RuntimeException('The number of replacements in the expression does not match the number of parameters'); } } return array(array( $expression, $parameters, $types )); } }