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/Router.php
Fabien Potencier b74a887cd9 minor #9487 unify constructor initialization style throughout symfony (Tobion)
This PR was merged into the master branch.

Discussion
----------

unify constructor initialization style throughout symfony

| Q             | A
| ------------- | ---
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | n/a

In almost all classes symfony uses property initialization when the value is static. Constructor initialization is only used for things that actually have logic, like passed parameters or dynamic values. IMHO it makes the code much more readable because property definition, phpdoc and default value is in one place. Also one can easily see what the constructor implements for logic like overridden default value of a parent class. Otherwise the real deal is just hidden behind 10 property initializations. One more advantage is that it requires less code. As you can see, the code was almost cut in half (210 additions and 395 deletions).
I unified it accordingly across symfony. Sometimes it was [not even consistent within one class](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Config/Definition/BaseNode.php#L32). At the same time I recognized some errors like missing parent constructor call, or undefined properties or private properties that are not even used.

I then realized that a few Kernel tests were not passing because they were deeply implementation specific like modifying booted flag with a custom `KernelForTest->setIsBooted();`. I improved and refactored the kernel tests in the __second commit__.

__Third commit__ unifies short ternary operator, e.g. `$foo ?: new Foo()`. __Forth commit__ unifies missing parentheses, e.g. `new Foo()`.

Commits
-------

077a089 unify missing parentheses
2888594 unify short ternary operator
2a9daff [HttpKernel] better written kernel tests
111ac18 unify constructor initialization style throughout symfony
2013-11-22 18:42:00 +01:00

324 lines
9.5 KiB
PHP

<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\ConfigCache;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Generator\ConfigurableRequirementsInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Generator\Dumper\GeneratorDumperInterface;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
use Symfony\Component\Routing\Matcher\Dumper\MatcherDumperInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* The Router class is an example of the integration of all pieces of the
* routing system for easier use.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Router implements RouterInterface, RequestMatcherInterface
{
/**
* @var UrlMatcherInterface|null
*/
protected $matcher;
/**
* @var UrlGeneratorInterface|null
*/
protected $generator;
/**
* @var RequestContext
*/
protected $context;
/**
* @var LoaderInterface
*/
protected $loader;
/**
* @var RouteCollection|null
*/
protected $collection;
/**
* @var mixed
*/
protected $resource;
/**
* @var array
*/
protected $options = array();
/**
* @var LoggerInterface|null
*/
protected $logger;
/**
* Constructor.
*
* @param LoaderInterface $loader A LoaderInterface instance
* @param mixed $resource The main resource to load
* @param array $options An array of options
* @param RequestContext $context The context
* @param LoggerInterface $logger A logger instance
*/
public function __construct(LoaderInterface $loader, $resource, array $options = array(), RequestContext $context = null, LoggerInterface $logger = null)
{
$this->loader = $loader;
$this->resource = $resource;
$this->logger = $logger;
$this->context = $context ?: new RequestContext();
$this->setOptions($options);
}
/**
* Sets options.
*
* Available options:
*
* * cache_dir: The cache directory (or null to disable caching)
* * debug: Whether to enable debugging or not (false by default)
* * resource_type: Type hint for the main resource (optional)
*
* @param array $options An array of options
*
* @throws \InvalidArgumentException When unsupported option is provided
*/
public function setOptions(array $options)
{
$this->options = array(
'cache_dir' => null,
'debug' => false,
'generator_class' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator',
'generator_base_class' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator',
'generator_dumper_class' => 'Symfony\\Component\\Routing\\Generator\\Dumper\\PhpGeneratorDumper',
'generator_cache_class' => 'ProjectUrlGenerator',
'matcher_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
'matcher_base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
'matcher_dumper_class' => 'Symfony\\Component\\Routing\\Matcher\\Dumper\\PhpMatcherDumper',
'matcher_cache_class' => 'ProjectUrlMatcher',
'resource_type' => null,
'strict_requirements' => true,
);
// check option names and live merge, if errors are encountered Exception will be thrown
$invalid = array();
foreach ($options as $key => $value) {
if (array_key_exists($key, $this->options)) {
$this->options[$key] = $value;
} else {
$invalid[] = $key;
}
}
if ($invalid) {
throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".', implode('", "', $invalid)));
}
}
/**
* Sets an option.
*
* @param string $key The key
* @param mixed $value The value
*
* @throws \InvalidArgumentException
*/
public function setOption($key, $value)
{
if (!array_key_exists($key, $this->options)) {
throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
}
$this->options[$key] = $value;
}
/**
* Gets an option value.
*
* @param string $key The key
*
* @return mixed The value
*
* @throws \InvalidArgumentException
*/
public function getOption($key)
{
if (!array_key_exists($key, $this->options)) {
throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
}
return $this->options[$key];
}
/**
* {@inheritdoc}
*/
public function getRouteCollection()
{
if (null === $this->collection) {
$this->collection = $this->loader->load($this->resource, $this->options['resource_type']);
}
return $this->collection;
}
/**
* {@inheritdoc}
*/
public function setContext(RequestContext $context)
{
$this->context = $context;
if (null !== $this->matcher) {
$this->getMatcher()->setContext($context);
}
if (null !== $this->generator) {
$this->getGenerator()->setContext($context);
}
}
/**
* {@inheritdoc}
*/
public function getContext()
{
return $this->context;
}
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
return $this->getGenerator()->generate($name, $parameters, $referenceType);
}
/**
* {@inheritdoc}
*/
public function match($pathinfo)
{
return $this->getMatcher()->match($pathinfo);
}
/**
* {@inheritdoc}
*/
public function matchRequest(Request $request)
{
$matcher = $this->getMatcher();
if (!$matcher instanceof RequestMatcherInterface) {
// fallback to the default UrlMatcherInterface
return $matcher->match($request->getPathInfo());
}
return $matcher->matchRequest($request);
}
/**
* Gets the UrlMatcher instance associated with this Router.
*
* @return UrlMatcherInterface A UrlMatcherInterface instance
*/
public function getMatcher()
{
if (null !== $this->matcher) {
return $this->matcher;
}
if (null === $this->options['cache_dir'] || null === $this->options['matcher_cache_class']) {
return $this->matcher = new $this->options['matcher_class']($this->getRouteCollection(), $this->context);
}
$class = $this->options['matcher_cache_class'];
$cache = new ConfigCache($this->options['cache_dir'].'/'.$class.'.php', $this->options['debug']);
if (!$cache->isFresh()) {
$dumper = $this->getMatcherDumperInstance();
$options = array(
'class' => $class,
'base_class' => $this->options['matcher_base_class'],
);
$cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
}
require_once $cache;
return $this->matcher = new $class($this->context);
}
/**
* Gets the UrlGenerator instance associated with this Router.
*
* @return UrlGeneratorInterface A UrlGeneratorInterface instance
*/
public function getGenerator()
{
if (null !== $this->generator) {
return $this->generator;
}
if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) {
$this->generator = new $this->options['generator_class']($this->getRouteCollection(), $this->context, $this->logger);
} else {
$class = $this->options['generator_cache_class'];
$cache = new ConfigCache($this->options['cache_dir'].'/'.$class.'.php', $this->options['debug']);
if (!$cache->isFresh()) {
$dumper = $this->getGeneratorDumperInstance();
$options = array(
'class' => $class,
'base_class' => $this->options['generator_base_class'],
);
$cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
}
require_once $cache;
$this->generator = new $class($this->context, $this->logger);
}
if ($this->generator instanceof ConfigurableRequirementsInterface) {
$this->generator->setStrictRequirements($this->options['strict_requirements']);
}
return $this->generator;
}
/**
* @return GeneratorDumperInterface
*/
protected function getGeneratorDumperInstance()
{
return new $this->options['generator_dumper_class']($this->getRouteCollection());
}
/**
* @return MatcherDumperInterface
*/
protected function getMatcherDumperInstance()
{
return new $this->options['matcher_dumper_class']($this->getRouteCollection());
}
}