This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/Routing/Loader/XmlFileLoader.php

190 lines
6.0 KiB
PHP
Raw Normal View History

2010-02-17 13:53:31 +00:00
<?php
/*
* This file is part of the Symfony package.
2010-02-17 13:53:31 +00:00
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
2010-02-17 13:53:31 +00:00
*/
namespace Symfony\Component\Routing\Loader;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Resource\FileResource;
2010-02-17 13:53:31 +00:00
/**
* XmlFileLoader loads XML routing files.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
2010-02-17 13:53:31 +00:00
*/
class XmlFileLoader extends FileLoader
{
/**
* Loads an XML file.
*
* @param string $file An XML file path
* @param string $type The resource type
*
* @return RouteCollection A RouteCollection instance
*
* @throws \InvalidArgumentException When a tag can't be parsed
*/
public function load($file, $type = null)
2010-02-17 13:53:31 +00:00
{
$path = $this->findFile($file);
$xml = $this->loadFile($path);
$collection = new RouteCollection();
$collection->addResource(new FileResource($path));
// process routes and imports
foreach ($xml->documentElement->childNodes as $node) {
if (!$node instanceof \DOMElement) {
continue;
}
switch ($node->tagName) {
case 'route':
$this->parseRoute($collection, $node, $path);
break;
case 'import':
$resource = (string) $node->getAttribute('resource');
$type = (string) $node->getAttribute('type');
$prefix = (string) $node->getAttribute('prefix');
$this->currentDir = dirname($path);
$collection->addCollection($this->import($resource, $type), $prefix);
break;
default:
throw new \InvalidArgumentException(sprintf('Unable to parse tag "%s"', $node->tagName));
}
}
return $collection;
2010-02-17 13:53:31 +00:00
}
/**
* Returns true if this class supports the given resource.
*
* @param mixed $resource A resource
* @param string $type The resource type
*
* @return boolean True if this class supports the given resource, false otherwise
*/
public function supports($resource, $type = null)
{
return is_string($resource) && 'xml' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'xml' === $type);
}
/**
* Parses a route and adds it to the RouteCollection.
*
* @param RouteCollection $collection A RouteCollection instance
* @param \DOMElement $definition Route definition
* @param string $file An XML file path
*
* @throws \InvalidArgumentException When the definition cannot be parsed
*/
protected function parseRoute(RouteCollection $collection, \DOMElement $definition, $file)
2010-02-17 13:53:31 +00:00
{
$defaults = array();
$requirements = array();
$options = array();
foreach ($definition->childNodes as $node) {
if (!$node instanceof \DOMElement) {
continue;
}
switch ($node->tagName) {
case 'default':
$defaults[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
break;
case 'option':
$options[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
break;
case 'requirement':
$requirements[(string) $node->getAttribute('key')] = trim((string) $node->nodeValue);
break;
default:
throw new \InvalidArgumentException(sprintf('Unable to parse tag "%s"', $node->tagName));
}
}
$route = new Route((string) $definition->getAttribute('pattern'), $defaults, $requirements, $options);
made some method name changes to have a better coherence throughout the framework When an object has a "main" many relation with related "things" (objects, parameters, ...), the method names are normalized: * get() * set() * all() * replace() * remove() * clear() * isEmpty() * add() * register() * count() * keys() The classes below follow this method naming convention: * BrowserKit\CookieJar -> Cookie * BrowserKit\History -> Request * Console\Application -> Command * Console\Application\Helper\HelperSet -> HelperInterface * DependencyInjection\Container -> services * DependencyInjection\ContainerBuilder -> services * DependencyInjection\ParameterBag\ParameterBag -> parameters * DependencyInjection\ParameterBag\FrozenParameterBag -> parameters * DomCrawler\Form -> FormField * EventDispatcher\Event -> parameters * Form\FieldGroup -> Field * HttpFoundation\HeaderBag -> headers * HttpFoundation\ParameterBag -> parameters * HttpFoundation\Session -> attributes * HttpKernel\Profiler\Profiler -> DataCollectorInterface * Routing\RouteCollection -> Route * Security\Authentication\AuthenticationProviderManager -> AuthenticationProviderInterface * Templating\Engine -> HelperInterface * Translation\MessageCatalogue -> messages The usage of these methods are only allowed when it is clear that there is a main relation: * a CookieJar has many Cookies; * a Container has many services and many parameters (as services is the main relation, we use the naming convention for this relation); * a Console Input has many arguments and many options. There is no "main" relation, and so the naming convention does not apply. For many relations where the convention does not apply, the following methods must be used instead (where XXX is the name of the related thing): * get() -> getXXX() * set() -> setXXX() * all() -> getXXXs() * replace() -> setXXXs() * remove() -> removeXXX() * clear() -> clearXXX() * isEmpty() -> isEmptyXXX() * add() -> addXXX() * register() -> registerXXX() * count() -> countXXX() * keys()
2010-11-23 08:42:19 +00:00
$collection->add((string) $definition->getAttribute('id'), $route);
2010-02-17 13:53:31 +00:00
}
/**
* Loads an XML file.
*
* @param string $file An XML file path
*
* @return \DOMDocument
*
* @throws \InvalidArgumentException When loading of XML file returns error
*/
protected function loadFile($file)
2010-02-17 13:53:31 +00:00
{
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
if (!$dom->load($file, LIBXML_COMPACT)) {
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
}
$dom->validateOnParse = true;
$dom->normalizeDocument();
libxml_use_internal_errors(false);
$this->validate($dom);
return $dom;
2010-02-17 13:53:31 +00:00
}
/**
* Validates a loaded XML file.
*
* @param \DOMDocument $dom A loaded XML file
*
* @throws \InvalidArgumentException When XML doesn't validate its XSD schema
*/
protected function validate(\DOMDocument $dom)
2010-02-17 13:53:31 +00:00
{
2010-05-21 15:18:29 +01:00
$parts = explode('/', str_replace('\\', '/', __DIR__.'/schema/routing/routing-1.0.xsd'));
$drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
$location = 'file:///'.$drive.implode('/', $parts);
2010-05-21 15:18:29 +01:00
$current = libxml_use_internal_errors(true);
if (!$dom->schemaValidate($location)) {
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
}
2010-05-21 15:18:29 +01:00
libxml_use_internal_errors($current);
2010-02-17 13:53:31 +00:00
}
/**
* Retrieves libxml errors and clears them.
*
* @return array An array of libxml error strings
*/
protected function getXmlErrors()
2010-02-17 13:53:31 +00:00
{
$errors = array();
foreach (libxml_get_errors() as $error) {
$errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
$error->code,
trim($error->message),
$error->file ? $error->file : 'n/a',
$error->line,
$error->column
);
}
libxml_clear_errors();
return $errors;
2010-02-17 13:53:31 +00:00
}
}