Validator.php 9.97 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
/*
 *  $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
19
 * <http://www.phpdoctrine.org>.
20
 */
21

22 23 24 25 26
/**
 * Doctrine_Validator
 * Doctrine_Validator performs validations in record properties
 *
 * @package     Doctrine
27
 * @subpackage  Validator
28 29 30 31 32 33
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 */
34
class Doctrine_Validator extends Doctrine_Locator_Injectable
35 36 37 38 39
{
    /**
     * @var array $validators           an array of validator objects
     */
    private static $validators  = array();
40

41 42 43 44 45 46 47 48 49
    /**
     * returns a validator object
     *
     * @param string $name
     * @return Doctrine_Validator_Interface
     */
    public static function getValidator($name)
    {
        if ( ! isset(self::$validators[$name])) {
50
            $class = 'Doctrine_Validator_' . ucwords(strtolower($name));
51 52 53
            if (class_exists($class)) {
                self::$validators[$name] = new $class;
            } else {
nicobn's avatar
nicobn committed
54
                throw new Doctrine_Exception("Validator named '$name' not available.");
55 56 57 58 59
            }

        }
        return self::$validators[$name];
    }
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    /**
     * validates a given record and saves possible errors
     * in Doctrine_Validator::$stack
     *
     * @param Doctrine_Record $record
     * @return void
     */
    public function validateRecord(Doctrine_Record $record)
    {
        $columns   = $record->getTable()->getColumns();
        $component = $record->getTable()->getComponentName();

        $errorStack = $record->getErrorStack();

        // if record is transient all fields will be validated
        // if record is persistent only the modified fields will be validated
        $data = ($record->exists()) ? $record->getModified() : $record->getData();

        $err      = array();
        foreach ($data as $key => $value) {
zYne's avatar
zYne committed
81
            if ($value === self::$_null) {
82
                $value = null;
83
            } else if ($value instanceof Doctrine_Record) {
84
                $value = $value->getIncremented();
zYne's avatar
zYne committed
85
            }
86

adamthehutt's avatar
adamthehutt committed
87
            $column = $columns[$record->getTable()->getColumnName($key)];
88

zYne's avatar
zYne committed
89
            if ($column['type'] == 'enum') {
90 91 92 93 94 95 96 97
                $value = $record->getTable()->enumIndex($key, $value);

                if ($value === false) {
                    $errorStack->add($key, 'enum');
                    continue;
                }
            }

98
            if ($record->getTable()->getAttribute(Doctrine::ATTR_VALIDATE) & Doctrine::VALIDATE_LENGTHS) {
99
                if ( ! $this->validateLength($column, $key, $value)) {
100
                    $errorStack->add($key, 'length');
zYne's avatar
zYne committed
101

102 103 104 105
                    continue;
                }
            }

zYne's avatar
zYne committed
106
            foreach ($column as $name => $args) {
107 108 109 110 111
                if (empty($name)
                    || $name == 'primary'
                    || $name == 'protected'
                    || $name == 'autoincrement'
                    || $name == 'default'
zYne's avatar
zYne committed
112 113
                    || $name == 'values'
                    || $name == 'sequence'
zYne's avatar
zYne committed
114 115
                    || $name == 'zerofill'
                    || $name == 'scale') {
116 117
                    continue;
                }
zYne's avatar
zYne committed
118 119 120 121 122

                if (strtolower($name) === 'notnull' && isset($column['autoincrement'])) {
                    continue;
                }

123
                if (strtolower($name) == 'length') {
124
                    if ( ! ($record->getTable()->getAttribute(Doctrine::ATTR_VALIDATE) & Doctrine::VALIDATE_LENGTHS)) {
125
                        if ( ! $this->validateLength($column, $key, $value)) {
126 127 128 129 130 131 132
                            $errorStack->add($key, 'length');
                        }
                    }
                    continue;
                }

                if (strtolower($name) == 'type') {
133
                    if ( ! ($record->getTable()->getAttribute(Doctrine::ATTR_VALIDATE) & Doctrine::VALIDATE_TYPES)) {
zYne's avatar
zYne committed
134
                        if ( ! self::isValidType($value, $column['type'])) {
135 136 137 138 139 140 141
                            $errorStack->add($key, 'type');
                        }
                    }
                    continue;
                }

                $validator = self::getValidator($name);
zYne's avatar
zYne committed
142 143 144 145 146
                $validator->invoker = $record;
                $validator->field   = $key;
                $validator->args    = $args;

                if ( ! $validator->validate($value)) {
147 148 149 150 151 152 153 154 155
                    $errorStack->add($key, $name);

                    //$err[$key] = 'not valid';

                    // errors found quit validation looping for this column
                    //break;
                }
            }

156
            if ($record->getTable()->getAttribute(Doctrine::ATTR_VALIDATE) & Doctrine::VALIDATE_TYPES) {
zYne's avatar
zYne committed
157
                if ( ! self::isValidType($value, $column['type'])) {
158 159 160 161 162 163
                    $errorStack->add($key, 'type');
                    continue;
                }
            }
        }
    }
164

165
    /**
166
     * Validates the length of a field.
167 168 169
     */
    private function validateLength($column, $key, $value)
    {
romanb's avatar
romanb committed
170 171
        if ($column['type'] == 'timestamp' || $column['type'] == 'integer' || 
                $column['type'] == 'enum') {
172
            return true;
romanb's avatar
romanb committed
173
        } else if ($column['type'] == 'array' || $column['type'] == 'object') {
174 175 176 177 178
            $length = strlen(serialize($value));
        } else {
            $length = strlen($value);
        }

zYne's avatar
zYne committed
179
        if ($length > $column['length']) {
180 181 182 183
            return false;
        }
        return true;
    }
184

185 186 187 188 189 190 191 192 193
    /**
     * whether or not this validator has errors
     *
     * @return boolean
     */
    public function hasErrors()
    {
        return (count($this->stack) > 0);
    }
194

195
    /**
zYne's avatar
zYne committed
196
     * phpType
197 198
     * converts a doctrine type to native php type
     *
zYne's avatar
zYne committed
199
     * @param $portableType     portable doctrine type
200
     * @return string
201
     *//*
zYne's avatar
zYne committed
202
    public static function phpType($portableType)
203
    {
zYne's avatar
zYne committed
204
        switch ($portableType) {
205 206 207 208 209 210 211 212 213 214 215
            case 'enum':
                return 'integer';
            case 'blob':
            case 'clob':
            case 'mbstring':
            case 'timestamp':
            case 'date':
            case 'gzip':
                return 'string';
                break;
            default:
zYne's avatar
zYne committed
216
                return $portableType;
217
        }
218
    }*/
219 220 221 222 223 224 225 226
    /**
     * returns whether or not the given variable is
     * valid type
     *
     * @param mixed $var
     * @param string $type
     * @return boolean
     */
227
     /*
228 229
    public static function isValidType($var, $type)
    {
zYne's avatar
zYne committed
230
        if ($type == 'boolean') {
231
            return true;
zYne's avatar
zYne committed
232
        }
233 234 235 236 237 238 239 240

        $looseType = self::gettype($var);
        $type      = self::phpType($type);

        switch ($looseType) {
            case 'float':
            case 'double':
            case 'integer':
zYne's avatar
zYne committed
241
                if ($type == 'string' || $type == 'float') {
242
                    return true;
zYne's avatar
zYne committed
243
                }
244 245 246 247 248 249 250 251
            case 'string':
            case 'array':
            case 'object':
                return ($type === $looseType);
                break;
            case 'NULL':
                return true;
                break;
zYne's avatar
zYne committed
252
        }
253 254 255 256 257 258 259 260 261 262 263
    }*/
    
    
    /**
     * returns whether or not the given variable is
     * valid type
     *
     * @param mixed $var
     * @param string $type
     * @return boolean
     */
romanb's avatar
romanb committed
264 265 266 267 268 269 270 271 272 273 274
     public static function isValidType($var, $type)
     {
         if ($var === null) {
             return true;
         } else if (is_object($var)) {
             return $type == 'object';
         }
     
         switch ($type) {
             case 'float':
             case 'double':
275
                 return (string)$var == strval(floatval($var));
romanb's avatar
romanb committed
276
             case 'integer':
277
                 return (string)$var == strval(intval($var));
romanb's avatar
romanb committed
278 279
             case 'string':
                 return is_string($var) || is_int($var) || is_float($var);
280 281 282 283
             case 'blob':
             case 'clob':
             case 'gzip':
                 return is_string($var);
romanb's avatar
romanb committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
             case 'array':
                 return is_array($var);
             case 'object':
                 return is_object($var);
             case 'boolean':
                 return is_bool($var);
             case 'timestamp':
                 // todo: validate the timestamp is in YYYY-MM-DD HH:MM:SS format
                 return true;
             case 'date':
                 $validator = self::getValidator('date');
                 return $validator->validate($var);
             case 'enum':
                 return is_string($var) || is_int($var);
             default:
                 return false;
         }
     }
302 303
    
    
304 305 306 307 308
    /**
     * returns the type of loosely typed variable
     *
     * @param mixed $var
     * @return string
309
     *//*
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
    public static function gettype($var)
    {
        $type = gettype($var);
        switch ($type) {
            case 'string':
                if (preg_match("/^[0-9]+$/",$var)) {
                    return 'integer';
                } elseif (is_numeric($var)) {
                    return 'float';
                } else {
                    return $type;
                }
                break;
            default:
                return $type;
zYne's avatar
zYne committed
325
        }
326
    }*/
327
}