# Source for file Expression.php

Documentation is available at Expression.php

1. <?php
2. /*
3. * $Id: Expression.php 2283 2007-08-28 19:51:06Z jackbravo $
4. *
5. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16. *
17. * This software consists of voluntary contributions made by many individuals
18. * and is licensed under the LGPL. For more information, see
19. * <http://www.phpdoctrine.com>.
20. */
21. Doctrine::autoload('Doctrine_Connection_Module');
22. /**
23. * Doctrine_Expression
24. *
25. * @package Doctrine
26. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
27. * @category Object Relational Mapping
28. * @link www.phpdoctrine.com
29. * @since 1.0
30. * @version $Revision: 2283 $
31. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
32. */
33. class Doctrine_Expression
34. {
35. protected $_expression;
37. protected $_conn;
39. public function __construct($expr, $conn = null)
40. {
41. $this->setExpression($expr);
43. if ($conn !== null) {
44. $this->_conn = $conn;
45. }
46. }
48. public function getConnection()
49. {
50. if ( ! isset($this->_conn)) {
51. return Doctrine_Manager::connection();
52. }
54. return $this->_conn;
55. }
57. public function setExpression($clause)
58. {
59. $this->_expression = $this->parseClause($clause);
60. }
62. public function parseExpression($expr)
63. {
64. $pos = strpos($expr, '(');
65. if ($pos === false) {
66. return $expr;
67. }
69. // get the name of the function
70. $name = substr($expr, 0, $pos);
71. $argStr = substr($expr, ($pos + 1), -1);
73. // parse args
74. foreach (Doctrine_Tokenizer::bracketExplode($argStr, ',') as $arg) {
75. $args[] = $this->parseClause($arg);
76. }
78. return call_user_func_array(array($this->getConnection()->expression, $name), $args);
79. }
81. public function parseClause($clause)
82. {
83. $e = Doctrine_Tokenizer::bracketExplode($clause, ' ');
85. foreach ($e as $k => $expr) {
86. $e[$k] = $this->parseExpression($expr);
87. }
89. return implode(' ', $e);
90. }
92. public function getSql()
93. {
95. return $this->_expression;
96. }
98. public function __toString()
99. {
100. return $this->getSql();
101. }
102. }