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: /**
27: * Indicates that the operation is in pre-order
28: *
29: */
30: const PREFIX = 0;
31:
32: /**
33: * Indicates that the operation is in post-order
34: *
35: */
36: const POSTFIX = 1;
37:
38: /**
39: * The operator this unary expression represents
40: *
41: * @var string
42: */
43: protected $_operator;
44:
45: /**
46: * Holds the value which the unary expression operates
47: *
48: * @var mixed
49: */
50: protected $_value;
51:
52: /**
53: * Where to place the operator
54: *
55: * @var int
56: */
57: protected $_mode;
58:
59: /**
60: * Constructor
61: *
62: * @param string $operator The operator to used for the expression
63: * @param mixed $value the value to use as the operand for the expression
64: * @param int $mode either UnaryExpression::PREFIX or UnaryExpression::POSTFIX
65: */
66: public function __construct($operator, $value, $mode = self::PREFIX)
67: {
68: $this->_operator = $operator;
69: $this->_value = $value;
70: $this->_mode = $mode;
71: }
72:
73: /**
74: * Converts the expression to its string representation
75: *
76: * @param \Cake\Database\ValueBinder $generator Placeholder generator object
77: * @return string
78: */
79: public function sql(ValueBinder $generator)
80: {
81: $operand = $this->_value;
82: if ($operand instanceof ExpressionInterface) {
83: $operand = $operand->sql($generator);
84: }
85:
86: if ($this->_mode === self::POSTFIX) {
87: return '(' . $operand . ') ' . $this->_operator;
88: }
89:
90: return $this->_operator . ' (' . $operand . ')';
91: }
92:
93: /**
94: * {@inheritDoc}
95: *
96: */
97: public function traverse(callable $callable)
98: {
99: if ($this->_value instanceof ExpressionInterface) {
100: $callable($this->_value);
101: $this->_value->traverse($callable);
102: }
103: }
104:
105: /**
106: * Perform a deep clone of the inner expression.
107: *
108: * @return void
109: */
110: public function __clone()
111: {
112: if ($this->_value instanceof ExpressionInterface) {
113: $this->_value = clone $this->_value;
114: }
115: }
116: }
117: