4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Mapping\Loader;
14 use Symfony\Component\Validator\Constraint;
15 use Symfony\Component\Validator\Exception\MappingException;
18 * Base loader for validation metadata.
20 * This loader supports the loading of constraints from Symfony's default
21 * namespace (see {@link DEFAULT_NAMESPACE}) using the short class names of
22 * those constraints. Constraints can also be loaded using their fully
23 * qualified class names. At last, namespace aliases can be defined to load
24 * constraints with the syntax "alias:ShortName".
26 * @author Bernhard Schussek <bschussek@gmail.com>
28 abstract class AbstractLoader implements LoaderInterface
31 * The namespace to load constraints from by default.
33 const DEFAULT_NAMESPACE = '\\Symfony\\Component\\Validator\\Constraints\\';
38 protected $namespaces = array();
41 * Adds a namespace alias.
43 * The namespace alias can be used to reference constraints from specific
44 * namespaces in {@link newConstraint()}:
46 * $this->addNamespaceAlias('mynamespace', '\\Acme\\Package\\Constraints\\');
48 * $constraint = $this->newConstraint('mynamespace:NotNull');
50 * @param string $alias The alias
51 * @param string $namespace The PHP namespace
53 protected function addNamespaceAlias($alias, $namespace)
55 $this->namespaces[$alias] = $namespace;
59 * Creates a new constraint instance for the given constraint name.
61 * @param string $name The constraint name. Either a constraint relative
62 * to the default constraint namespace, or a fully
63 * qualified class name. Alternatively, the constraint
64 * may be preceded by a namespace alias and a colon.
65 * The namespace alias must have been defined using
66 * {@link addNamespaceAlias()}.
67 * @param mixed $options The constraint options
71 * @throws MappingException If the namespace prefix is undefined
73 protected function newConstraint($name, $options = null)
75 if (strpos($name, '\\') !== false && class_exists($name)) {
76 $className = (string) $name;
77 } elseif (strpos($name, ':') !== false) {
78 list($prefix, $className) = explode(':', $name, 2);
80 if (!isset($this->namespaces[$prefix])) {
81 throw new MappingException(sprintf('Undefined namespace prefix "%s"', $prefix));
84 $className = $this->namespaces[$prefix].$className;
86 $className = self::DEFAULT_NAMESPACE.$name;
89 return new $className($options);