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