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\Routing\Generator\Dumper;
15 * PhpGeneratorDumper creates a PHP class able to generate URLs for a given set of routes.
17 * @author Fabien Potencier <fabien@symfony.com>
18 * @author Tobias Schultze <http://tobion.de>
20 class PhpGeneratorDumper extends GeneratorDumper
23 * Dumps a set of routes to a PHP class.
27 * * class: The class name
28 * * base_class: The base class name
30 * @param array $options An array of options
32 * @return string A PHP class representing the generator class
34 public function dump(array $options = array())
36 $options = array_merge(array(
37 'class' => 'ProjectUrlGenerator',
38 'base_class' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator',
44 use Symfony\Component\Routing\RequestContext;
45 use Symfony\Component\Routing\Exception\RouteNotFoundException;
46 use Psr\Log\LoggerInterface;
49 * This class has been auto-generated
50 * by the Symfony Routing Component.
52 class {$options['class']} extends {$options['base_class']}
54 private static \$declaredRoutes;
56 public function __construct(RequestContext \$context, LoggerInterface \$logger = null)
58 \$this->context = \$context;
59 \$this->logger = \$logger;
60 if (null === self::\$declaredRoutes) {
61 self::\$declaredRoutes = {$this->generateDeclaredRoutes()};
65 {$this->generateGenerateMethod()}
72 * Generates PHP code representing an array of defined routes
73 * together with the routes properties (e.g. requirements).
75 * @return string PHP code
77 private function generateDeclaredRoutes()
80 foreach ($this->getRoutes()->all() as $name => $route) {
81 $compiledRoute = $route->compile();
83 $properties = array();
84 $properties[] = $compiledRoute->getVariables();
85 $properties[] = $route->getDefaults();
86 $properties[] = $route->getRequirements();
87 $properties[] = $compiledRoute->getTokens();
88 $properties[] = $compiledRoute->getHostTokens();
89 $properties[] = $route->getSchemes();
91 $routes .= sprintf(" '%s' => %s,\n", $name, str_replace("\n", '', var_export($properties, true)));
99 * Generates PHP code representing the `generate` method that implements the UrlGeneratorInterface.
101 * @return string PHP code
103 private function generateGenerateMethod()
106 public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
108 if (!isset(self::$declaredRoutes[$name])) {
109 throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
112 list($variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes) = self::$declaredRoutes[$name];
114 return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes);