* @package Mammut\DB\Sql */ class Calc extends \Mammut\StrictObject implements iExprCalc, iExprValue { protected $elements = array(); protected $unnest = null; public function __construct($basecontent, $type = self::TYPE_IDENTIFIER) { if($basecontent instanceof Parameter) $contenttype = self::TYPE_PARAMETER; $e = new \stdClass(); $e->value = $basecontent; $e->valuetype = $type; $this->elements[] = $e; } /** * * @param mixed $a * @param mixed $b * @return \Mammut\DB\Sql\Expression\Calc */ public static function newC($a, $typeA = self::TYPE_IDENTIFIER) { $obj = new self($a, $typeA); return $obj; } /** * Begin nesting calc * * @return Calc */ public function nest($operation, $basecontent, $type = self::TYPE_IDENTIFIER) { $calc = new self($basecontent, $type); $calc->setUnnest($this); $this->addOperation($operation, $calc, self::TYPE_EXPRESSION); return $calc; } /** * Indicate end of nested calc * * @return Calc * @throws \RuntimeException */ public function unnest() { if($this->unnest == null) throw new \RuntimeException('Not nested'); $unnset = $this->unnest; $this->unnest = null; return $unnset; } /** * Indicate what predicate will be unnested * * @param Calc $calc * @return void */ public function setUnnest(Calc $calc) { $this->unnest = $calc; } public function addOperation($operator, $content, $type = self::TYPE_VALUE) { $allowed = [self::OP_ADD,self::OP_SUB,self::OP_MULT,self::OP_DIV,self::OP_MOD]; if (!in_array($operator, $allowed)) throw new \InvalidArgumentException('invalid operator'); $o = new \stdClass(); $o->operator = $operator; $o->value = $content; $o->valuetype = $type; $this->elements[] = $o; return $this; } /** * * @param mixed $content * @param string $type * @return Calc */ public function add($content, $type = self::TYPE_VALUE) { return $this->addOperation(self::OP_ADD, $content, $type); } /** * * @param mixed $content * @param string $type * @return Calc */ public function sub($content, $type = self::TYPE_VALUE) { return $this->addOperation(self::OP_SUB, $content, $type); } /** * * @param mixed $content * @param string $type * @return Calc */ public function mult($content, $type = self::TYPE_VALUE) { return $this->addOperation(self::OP_MULT, $content, $type); } /** * * @param mixed $content * @param string $type * @return Calc */ public function div($content, $type = self::TYPE_VALUE) { return $this->addOperation(self::OP_DIV, $content, $type); } public function getElements() { return $this->elements; } }