1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since 3.0.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\Database\Expression;
16:
17: use Cake\Database\ExpressionInterface;
18: use Cake\Database\ValueBinder;
19:
20: /**
21: * An expression object that represents an expression with only a single operand.
22: */
23: class UnaryExpression implements ExpressionInterface
24: {
25: /**
26: * Indicates that the operation is in pre-order
27: *
28: */
29: const PREFIX = 0;
30:
31: /**
32: * Indicates that the operation is in post-order
33: *
34: */
35: const POSTFIX = 1;
36:
37: /**
38: * The operator this unary expression represents
39: *
40: * @var string
41: */
42: protected $_operator;
43:
44: /**
45: * Holds the value which the unary expression operates
46: *
47: * @var mixed
48: */
49: protected $_value;
50:
51: /**
52: * Where to place the operator
53: *
54: * @var int
55: */
56: protected $_mode;
57:
58: /**
59: * Constructor
60: *
61: * @param string $operator The operator to used for the expression
62: * @param mixed $value the value to use as the operand for the expression
63: * @param int $mode either UnaryExpression::PREFIX or UnaryExpression::POSTFIX
64: */
65: public function __construct($operator, $value, $mode = self::PREFIX)
66: {
67: $this->_operator = $operator;
68: $this->_value = $value;
69: $this->_mode = $mode;
70: }
71:
72: /**
73: * Converts the expression to its string representation
74: *
75: * @param \Cake\Database\ValueBinder $generator Placeholder generator object
76: * @return string
77: */
78: public function sql(ValueBinder $generator)
79: {
80: $operand = $this->_value;
81: if ($operand instanceof ExpressionInterface) {
82: $operand = $operand->sql($generator);
83: }
84:
85: if ($this->_mode === self::POSTFIX) {
86: return '(' . $operand . ') ' . $this->_operator;
87: }
88:
89: return $this->_operator . ' (' . $operand . ')';
90: }
91:
92: /**
93: * {@inheritDoc}
94: *
95: */
96: public function traverse(callable $callable)
97: {
98: if ($this->_value instanceof ExpressionInterface) {
99: $callable($this->_value);
100: $this->_value->traverse($callable);
101: }
102: }
103:
104: /**
105: * Perform a deep clone of the inner expression.
106: *
107: * @return void
108: */
109: public function __clone()
110: {
111: if ($this->_value instanceof ExpressionInterface) {
112: $this->_value = clone $this->_value;
113: }
114: }
115: }
116: