1: <?php
2: /**
3: * This file contains the validator factory class.
4: *
5: * @package Core
6: * @subpackage Validation
7: * @version SVN Revision $Rev:$
8: *
9: * @author Murat Purc <murat@purc.de>
10: * @copyright four for business AG <www.4fb.de>
11: * @license http://www.contenido.org/license/LIZENZ.txt
12: * @link http://www.4fb.de
13: * @link http://www.contenido.org
14: */
15:
16: defined('CON_FRAMEWORK') || die('Illegal call: Missing framework initialization - request aborted.');
17:
18: /**
19: * Validator factory
20: *
21: * @package Core
22: * @subpackage Validation
23: */
24: class cValidatorFactory {
25:
26: /**
27: * Instantiates and returns the validator. Sets also validators default options.
28: *
29: * Each validator can be configured through CONTENIDO $cfg configuration variable.
30: * Example for email validator:
31: * <pre>
32: * $cfg['validator']['email'] = array(
33: * // List of top level domains to disallow
34: * 'disallow_tld' => array('.test', '.example', '.invalid', '.localhost'),
35: * // List of hosts to disallow
36: * 'disallow_host' => array('example.com', 'example.org', 'example.net'),
37: * // Flag to check DNS records for MX type
38: * 'mx_check' => false,
39: * );
40: * </pre>
41: *
42: * @param string $validator Validator to get
43: * @param array $options Options to use for the validator. Any passed option
44: * overwrites the related option in global validator configuration.
45: * @throws cInvalidArgumentException If type of validator is unknown or not available or if someone
46: * tries to get cValidatorFactory instance.
47: * @return cValidatorAbstract
48: */
49: public static function getInstance($validator, array $options = array()) {
50: global $cfg;
51:
52: $name = strtolower($validator);
53: $className = 'cValidator' . ucfirst($name);
54:
55: if ('factory' === $name) {
56: throw new cInvalidArgumentException("Can't use validator factory '{$validator}' as validator!");
57: }
58:
59: if (class_exists($className)) {
60: $obj = new $className();
61: } else {
62: // Try to load validator class file (in this folder)
63: $path = str_replace('\\', '/', dirname(__FILE__)) . '/';
64: $fileName = sprintf('class.validator.%s.php', $name);
65: if (!cFileHandler::exists($path . $fileName)) {
66: throw new cInvalidArgumentException("The file '{$fileName}' for validator '{$validator}' couldn't included by cValidatorFactory!");
67: }
68:
69: // Try to instantiate the class
70: require_once($path . $fileName);
71: if (!class_exists($className)) {
72: throw new cInvalidArgumentException("Missing validator class '{$className}' for validator '{$validator}' !");
73: }
74: $obj = new $className();
75: }
76:
77: // Merge passed options with global configured options.
78: if (isset($cfg['validator']) && isset($cfg['validator'][$name]) && is_array($cfg['validator'][$name])) {
79: $options = array_merge($cfg['validator'][$name], $options);
80: }
81: $obj->setOptions($options);
82:
83: return new $obj;
84: }
85:
86: }
87: