Where.php 9.08 KB
Newer Older
doctrine's avatar
doctrine committed
1
<?php
zYne's avatar
zYne committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
Doctrine::autoload('Doctrine_Query_Condition');
/**
 * Doctrine_Query_Where
 *
 * @package     Doctrine
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 */
lsmith's avatar
lsmith committed
33 34
class Doctrine_Query_Where extends Doctrine_Query_Condition
{
zYne's avatar
zYne committed
35 36 37 38 39 40 41 42 43
    public function parse($str, $append = false)
    {
        if ($append) {
            $this->query->addQueryPart('where', $this->_parse($str));
        } else {
            $this->query->setQueryPart('where', $this->_parse($str));
        }
        return $this->query;
    }
doctrine's avatar
doctrine committed
44
    /**
45
     * load
doctrine's avatar
doctrine committed
46 47 48 49 50
     * returns the parsed query part
     *
     * @param string $where
     * @return string
     */
lsmith's avatar
lsmith committed
51 52
    public function load($where)
    {
53 54
        $where = trim($where);

zYne's avatar
zYne committed
55
        $e     = Doctrine_Tokenizer::sqlExplode($where);
56

lsmith's avatar
lsmith committed
57
        if (count($e) > 1) {
58
            $tmp   = $e[0] . ' ' . $e[1];
59

lsmith's avatar
lsmith committed
60
            if (substr($tmp, 0, 6) == 'EXISTS') {
61
                return $this->parseExists($where, true);
lsmith's avatar
lsmith committed
62
            } elseif (substr($where, 0, 10) == 'NOT EXISTS') {
63
                return $this->parseExists($where, false);
lsmith's avatar
lsmith committed
64
            }
65
        }
66

lsmith's avatar
lsmith committed
67
        if (count($e) < 3) {
zYne's avatar
zYne committed
68
            $e = Doctrine_Tokenizer::sqlExplode($where, array('=', '<', '>', '!='));
zYne's avatar
zYne committed
69
        }
doctrine's avatar
doctrine committed
70
        $r = array_shift($e);
zYne's avatar
zYne committed
71

72
        $a = explode('.', $r);
doctrine's avatar
doctrine committed
73

lsmith's avatar
lsmith committed
74
        if (count($a) > 1) {
doctrine's avatar
doctrine committed
75
            $field     = array_pop($a);
76 77 78
            $count     = count($e);
            $slice     = array_slice($e, -1, 1);
            $value     = implode('', $slice);
zYne's avatar
zYne committed
79
            $operator  = trim(substr($where, strlen($r), -strlen($value)));
80

zYne's avatar
zYne committed
81
            $reference = implode('.', $a);
doctrine's avatar
doctrine committed
82 83
            $count     = count($a);

zYne's avatar
zYne committed
84
            $pos       = strpos($field, '(');
85

lsmith's avatar
lsmith committed
86
            if ($pos !== false) {
87
                $func   = substr($field, 0, $pos);
88
                $value  = trim(substr($field, ($pos + 1), -1));
89 90 91 92

                $values = Doctrine_Query::sqlExplode($value, ',');

                $field      = array_pop($a);
zYne's avatar
zYne committed
93
                $reference  = implode('.', $a);
94
                $table      = $this->query->load($reference, false);
zYne's avatar
zYne committed
95 96
                $field      = $table->getColumnName($field);

zYne's avatar
zYne committed
97
                array_pop($a);
zYne's avatar
zYne committed
98
                
zYne's avatar
zYne committed
99
                $reference2 = implode('.', $a);
zYne's avatar
zYne committed
100
                
101
                $alias      = $this->query->getTableAlias($reference2);
102

zYne's avatar
zYne committed
103 104
                $stack      = $this->query->getRelationStack();
                $relation   = end($stack);
lsmith's avatar
lsmith committed
105

zYne's avatar
zYne committed
106 107
                $stack      = $this->query->getTableStack();

lsmith's avatar
lsmith committed
108
                switch ($func) {
109 110 111 112
                    case 'contains':
                    case 'regexp':
                    case 'like':
                        $operator = $this->getOperator($func);
lsmith's avatar
lsmith committed
113

114 115 116 117 118
                        if (empty($relation)) {
                            throw new Doctrine_Query_Exception('DQL functions contains/regexp/like can only be used for fields of related components');
                        }
                        $where = array();
                        foreach ($values as $value) {
zYne's avatar
zYne committed
119 120
                            $where[] = $alias . '.' . $relation->getLocal() 
                                     . ' IN (SELECT '.$relation->getForeign()
zYne's avatar
zYne committed
121
                                     . ' FROM ' . $relation->getTable()->getTableName()
zYne's avatar
zYne committed
122
                                     . ' WHERE ' . $field . $operator . $value . ')';
123 124 125 126 127
                        }
                        $where = implode(' AND ', $where);
                        break;
                    default:
                        throw new Doctrine_Query_Exception('Unknown DQL function: '.$func);
zYne's avatar
zYne committed
128 129
                }
            } else {
zYne's avatar
zYne committed
130 131 132 133 134 135
                $map = $this->query->load($reference, false);

                $alias = $this->query->getTableAlias($reference);
                $table = $map['table'];

                $field = $table->getColumnName($field);
136 137 138
                // check if value is enumerated value
                $enumIndex = $table->enumIndex($field, trim($value, "'"));

lsmith's avatar
lsmith committed
139
                if (substr($value, 0, 1) == '(') {
140
                    // trim brackets
zYne's avatar
zYne committed
141
                    $trimmed   = Doctrine_Tokenizer::bracketTrim($value);
142

lsmith's avatar
lsmith committed
143
                    if (substr($trimmed, 0, 4) == 'FROM' || substr($trimmed, 0, 6) == 'SELECT') {
144 145
                        // subquery found
                        $q     = new Doctrine_Query();
zYne's avatar
zYne committed
146 147
                        $value = '(' . $q->isSubquery(true)->parseQuery($trimmed)->getQuery() . ')';

lsmith's avatar
lsmith committed
148
                    } elseif (substr($trimmed, 0, 4) == 'SQL:') {
149 150 151
                        $value = '(' . substr($trimmed, 4) . ')';
                    } else {
                        // simple in expression found
zYne's avatar
zYne committed
152
                        $e     = Doctrine_Tokenizer::sqlExplode($trimmed, ',');
lsmith's avatar
lsmith committed
153

154
                        $value = array();
lsmith's avatar
lsmith committed
155
                        foreach ($e as $part) {
zYne's avatar
zYne committed
156 157
                            $index = $table->enumIndex($field, trim($part, "'"));

lsmith's avatar
lsmith committed
158
                            if ($index !== false) {
159
                                $value[] = $index;
lsmith's avatar
lsmith committed
160
                            } else {
161
                                $value[] = $this->parseLiteralValue($part);
lsmith's avatar
lsmith committed
162
                            }
163
                        }
164
                        $value = '(' . implode(', ', $value) . ')';
165
                    }
zYne's avatar
zYne committed
166 167 168 169 170 171 172
                } elseif(substr($value, 0, 1) == ':' || $value === '?') {
                    // placeholder found
                    if ($table->getTypeOf($field) == 'enum') {
                        $this->query->addEnumParam($value, $table, $field);
                    } else {
                        $this->query->addEnumParam($value, null, null);
                    }
173
                } else {
lsmith's avatar
lsmith committed
174
                    if ($enumIndex !== false) {
175
                        $value = $enumIndex;
lsmith's avatar
lsmith committed
176
                    } else {
177
                        $value = $this->parseLiteralValue($value);
lsmith's avatar
lsmith committed
178
                    }
179
                }
zYne's avatar
zYne committed
180

lsmith's avatar
lsmith committed
181
                switch ($operator) {
182 183 184 185 186 187 188 189
                    case '<':
                    case '>':
                    case '=':
                    case '!=':
                        if ($enumIndex !== false) {
                            $value  = $enumIndex;
                        }
                    default:
190 191 192 193 194 195 196

                        if ($this->query->getType() === Doctrine_Query::SELECT) {
                            $fieldname = $alias ? $alias . '.' . $field : $field;
                        } else {
                            $fieldname = $field;
                        }
                        
zYne's avatar
zYne committed
197 198
                        $where = $fieldname . ' '
                               . $operator . ' ' . $value;
zYne's avatar
zYne committed
199
                }
200
            }
zYne's avatar
zYne committed
201
        }
doctrine's avatar
doctrine committed
202 203
        return $where;
    }
zYne's avatar
zYne committed
204 205 206 207 208 209 210
    /**
     * parses an EXISTS expression
     *
     * @param string $where         query where part to be parsed
     * @param boolean $negation     whether or not to use the NOT keyword
     * @return string
     */
lsmith's avatar
lsmith committed
211 212
    public function parseExists($where, $negation)
    {
213 214 215
        $operator = ($negation) ? 'EXISTS' : 'NOT EXISTS';

        $pos = strpos($where, '(');
lsmith's avatar
lsmith committed
216

zYne's avatar
zYne committed
217
        if ($pos == false) {
218
            throw new Doctrine_Query_Exception("Unknown expression, expected '('");
zYne's avatar
zYne committed
219
        }
220

zYne's avatar
zYne committed
221
        $sub = Doctrine_Tokenizer::bracketTrim(substr($where, $pos));
222

zYne's avatar
zYne committed
223
        return $operator . ' (' . $this->query->createSubquery()->parseQuery($sub, false)->getQuery() . ')';
224
    }
zYne's avatar
zYne committed
225 226 227 228 229 230
    /**
     * getOperator
     *
     * @param string $func
     * @return string
     */
lsmith's avatar
lsmith committed
231 232
    public function getOperator($func)
    {
lsmith's avatar
lsmith committed
233
        switch ($func) {
234 235 236 237 238 239 240 241 242
            case 'contains':
                $operator = ' = ';
                break;
            case 'regexp':
                $operator = $this->query->getConnection()->getRegexpOperator();
                break;
            case 'like':
                $operator = ' LIKE ';
                break;
243 244 245
        }
        return $operator;
    }
doctrine's avatar
doctrine committed
246
}