Coverage for Doctrine_Validator

Back to coverage report

1 <?php
2 /*
3  *  $Id: Validator.php 4069 2008-03-21 04:54:46Z jwage $
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.org>.
20  */
21
22 /**
23  * Doctrine_Validator
24  * Doctrine_Validator performs validations on record properties
25  *
26  * @package     Doctrine
27  * @subpackage  Validator
28  * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
29  * @link        www.phpdoctrine.org
30  * @since       1.0
31  * @version     $Revision: 4069 $
32  * @author      Roman Borschel <roman@code-factory.org>
33  * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
34  */
35 class Doctrine_Validator extends Doctrine_Locator_Injectable
36 {
37     /**
38      * @var array $validators           an array of validator objects
39      */
40     private static $validators = array();
41
42     /**
43      * returns a validator object
44      *
45      * @param string $name
46      * @return Doctrine_Validator_Interface
47      */
48     public static function getValidator($name)
49     {
50         if ( ! isset(self::$validators[$name])) {
51             $class = 'Doctrine_Validator_' . ucwords(strtolower($name));
52             if (class_exists($class)) {
53                 self::$validators[$name] = new $class;
54             } else if (class_exists($name)) {
55                 self::$validators[$name] = new $name;
56             } else {
57                 throw new Doctrine_Exception("Validator named '$name' not available.");
58             }
59
60         }
61         return self::$validators[$name];
62     }
63
64     /**
65      * validates a given record and saves possible errors
66      * in Doctrine_Validator::$stack
67      *
68      * @param Doctrine_Record $record
69      * @return void
70      */
71     public function validateRecord(Doctrine_Record $record)
72     {
73         $table = $record->getTable();
74         $columns   = $table->getColumns();
75         $component = $table->getComponentName();
76
77         $errorStack = $record->getErrorStack();
78
79         // if record is transient all fields will be validated
80         // if record is persistent only the modified fields will be validated
81         $fields = ($record->exists()) ? $record->getModified() : $record->getData();
82         $err = array();
83         foreach ($fields as $fieldName => $value) {
84             if ($value === self::$_null) {
85                 $value = null;
86             } else if ($value instanceof Doctrine_Record) {
87                 $value = $value->getIncremented();
88             }
89             
90             $dataType = $table->getTypeOf($fieldName);
91
92             // Validate field type, if type validation is enabled
93             if ($table->getAttribute(Doctrine::ATTR_VALIDATE) & Doctrine::VALIDATE_TYPES) {
94                 if ( ! self::isValidType($value, $dataType)) {
95                     $errorStack->add($fieldName, 'type');
96                 }
97                 if ($dataType == 'enum') {
98                     $enumIndex = $table->enumIndex($fieldName, $value);
99                     if ($enumIndex === false) {
100                         $errorStack->add($fieldName, 'enum');
101                     }
102                 }
103             }
104             
105             // Validate field length, if length validation is enabled
106             if ($table->getAttribute(Doctrine::ATTR_VALIDATE) & Doctrine::VALIDATE_LENGTHS) {
107                 if ( ! $this->validateLength($value, $dataType, $table->getFieldLength($fieldName))) {
108                     $errorStack->add($fieldName, 'length');
109                 }
110             }
111
112             // Run all custom validators
113             foreach ($table->getFieldValidators($fieldName) as $validatorName => $args) {
114                 if ( ! is_string($validatorName)) {
115                     $validatorName = $args;
116                     $args = array();
117                 }
118                 $validator = self::getValidator($validatorName);
119                 $validator->invoker = $record;
120                 $validator->field = $fieldName;
121                 $validator->args = $args;
122                 if ( ! $validator->validate($value)) {
123                     $errorStack->add($fieldName, $validatorName);
124                 }
125             }
126         }
127     }
128
129     /**
130      * Validates the length of a field.
131      */
132     private function validateLength($value, $type, $maximumLength)
133     {
134         if ($type == 'timestamp' || $type == 'integer' || $type == 'enum') {
135             return true;
136         } else if ($type == 'array' || $type == 'object') {
137             $length = strlen(serialize($value));
138         } else {
139             $length = strlen($value);
140         }
141         if ($length > $maximumLength) {
142             return false;
143         }
144         return true;
145     }
146
147     /**
148      * whether or not this validator has errors
149      *
150      * @return boolean
151      */
152     public function hasErrors()
153     {
154         return (count($this->stack) > 0);
155     }    
156     
157     /**
158      * returns whether or not the given variable is
159      * valid type
160      *
161      * @param mixed $var
162      * @param string $type
163      * @return boolean
164      */
165      public static function isValidType($var, $type)
166      {
167          if ($var === null) {
168              return true;
169          } else if (is_object($var)) {
170              return $type == 'object';
171          }
172      
173          switch ($type) {
174              case 'float':
175              case 'double':
176              case 'decimal':
177                  return (string)$var == strval(floatval($var));
178              case 'integer':
179                  return (string)$var == strval(intval($var));
180              case 'string':
181                  return is_string($var) || is_int($var) || is_float($var);
182              case 'blob':
183              case 'clob':
184              case 'gzip':
185                  return is_string($var);
186              case 'array':
187                  return is_array($var);
188              case 'object':
189                  return is_object($var);
190              case 'boolean':
191                  return is_bool($var);
192              case 'timestamp':
193                  $validator = self::getValidator('timestamp');
194                  return $validator->validate($var);
195              case 'time':
196                  $validator = self::getValidator('time');
197                  return $validator->validate($var);
198              case 'date':
199                  $validator = self::getValidator('date');
200                  return $validator->validate($var);
201              case 'enum':
202                  return is_string($var) || is_int($var);
203              default:
204                  return false;
205          }
206      }
207 }