本文整理汇总了PHP中Symfony\Component\Routing\Route::getDefaults方法的典型用法代码示例。如果您正苦于以下问题:PHP Route::getDefaults方法的具体用法?PHP Route::getDefaults怎么用?PHP Route::getDefaults使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\Routing\Route
的用法示例。
在下文中一共展示了Route::getDefaults方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testDefaults
public function testDefaults()
{
$route = new Route('/:foo');
$route->setDefaults(array('foo' => 'bar'));
$this->assertEquals(array('foo' => 'bar'), $route->getDefaults(), '->setDefaults() sets the defaults');
$this->assertEquals($route, $route->setDefaults(array()), '->setDefaults() implements a fluent interface');
}
示例2: createFromRoute
public function createFromRoute(Route $route)
{
$compiledRoute = $route->compile();
$defaults = array_intersect_key($route->getDefaults(), array_fill_keys($compiledRoute->getVariables(), null));
$tokens = $compiledRoute->getTokens();
return new ExtractedRoute($tokens, $defaults);
}
示例3: validateRoute
/**
* @param string $controller
*
* @throws InvalidRouteException
* @throws UnsupportedRouteFormatException
*/
private function validateRoute(Route $route)
{
if (!isset($route->getDefaults()['_controller'])) {
throw new InvalidRouteException('_controller property is not set.');
}
$controller = $route->getDefaults()['_controller'];
if (substr_count($controller, ':') === 2 && strpos($controller, '::') !== false) {
// Controller was in the `Bundle:Controller:Action` notation.
// It will have been parsed to `Org\Bundle\XBundle\Controller\YController::somethingAction`.
list($className, $methodName) = explode('::', $controller, 2);
if (!class_exists($className)) {
throw new InvalidRouteException(sprintf('Class "%s" does not exist.', $className));
}
$this->validatePublicMethodExistsInClass($className, $methodName);
} elseif (substr_count($controller, ':') === 2 && strpos($controller, '::') === false) {
// Controller is in the `Bundle:Controller:Action` notation.
try {
$controller = $this->controllerNameParser->parse($controller);
} catch (\InvalidArgumentException $e) {
// The exception message if the bundle does not exist has changed after Symfony 2.5.
// Use our own message for consistency.
$isBundleDoesNotExistException = strpos($e->getMessage(), 'does not exist or it is not enabled') !== false || strpos($e->getMessage(), ' does not exist or is not enabled in your kernel') !== false;
if ($isBundleDoesNotExistException) {
$bundle = substr($controller, 0, strpos($controller, ':'));
$message = sprintf('Bundle "%s" (from the _controller value "%s") does not exist, or is it not enabled', $bundle, $controller);
throw new InvalidRouteException($message, null, $e);
}
throw new InvalidRouteException($e->getMessage(), null, $e);
}
// Controller will now have been parsed to
// `Org\Bundle\XBundle\Controller\YController::somethingAction`.
list($className, $methodName) = explode('::', $controller, 2);
$this->validatePublicMethodExistsInClass($className, $methodName);
} elseif (substr_count($controller, ':') === 1) {
// Controller is in the `service:method` notation.
list($service, $methodName) = explode(':', $controller, 2);
try {
$serviceInstance = $this->container->get($service);
} catch (ServiceNotFoundException $e) {
throw new InvalidRouteException($e->getMessage(), null, $e);
}
$this->validatePublicMethodExistsInClass(get_class($serviceInstance), $methodName);
} else {
throw new UnsupportedRouteFormatException(sprintf('Route format "%s" is not supported by this tool', $controller));
}
}
示例4: getAttributes
/**
* {@inheritdoc}
*/
protected function getAttributes(Route $route, $name, array $attributes)
{
if ($route instanceof RouteObjectInterface && is_string($route->getRouteKey())) {
$name = $route->getRouteKey();
}
$attributes[RouteObjectInterface::ROUTE_NAME] = $name;
$attributes[RouteObjectInterface::ROUTE_OBJECT] = $route;
return $this->mergeDefaults($attributes, $route->getDefaults());
}
示例5: testDefaults
/**
* @covers Symfony\Component\Routing\Route::setDefaults
* @covers Symfony\Component\Routing\Route::getDefaults
* @covers Symfony\Component\Routing\Route::setDefault
* @covers Symfony\Component\Routing\Route::getDefault
*/
public function testDefaults()
{
$route = new Route('/{foo}');
$route->setDefaults(array('foo' => 'bar'));
$this->assertEquals(array('foo' => 'bar'), $route->getDefaults(), '->setDefaults() sets the defaults');
$this->assertEquals($route, $route->setDefaults(array()), '->setDefaults() implements a fluent interface');
$route->setDefault('foo', 'bar');
$this->assertEquals('bar', $route->getDefault('foo'), '->setDefault() sets a default value');
$route->setDefault('foo2', 'bar2');
$this->assertEquals('bar2', $route->getDefault('foo2'), '->getDefault() return the default value');
$this->assertNull($route->getDefault('not_defined'), '->getDefault() return null if default value is not setted');
}
示例6: extractRawAttributes
/**
* Extracts all of the raw attributes from a path for a given route.
*
* @param \Symfony\Component\Routing\Route $route
* The route object.
* @param string $name
* The route name.
* @param string $path
* A path.
*
* @return array
* An array of raw attributes for this path and route.
*/
public static function extractRawAttributes(Route $route, $name, $path)
{
// See \Symfony\Component\Routing\Matcher\UrlMatcher::matchCollection().
preg_match($route->compile()->getRegex(), $path, $matches);
// See \Symfony\Component\Routing\Matcher\UrlMatcher::mergeDefaults().
$attributes = $route->getDefaults();
foreach ($matches as $key => $value) {
if (!is_int($key)) {
$attributes[$key] = $value;
}
}
// See \Symfony\Cmf\Component\Routing\NestedMatcher\UrlMatcher::getAttributes().
$attributes[RouteObjectInterface::ROUTE_OBJECT] = $route;
$attributes[RouteObjectInterface::ROUTE_NAME] = $name;
return $attributes;
}
示例7: generate
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
try {
if ($name instanceof SeoAwareInterface) {
$documentUrl = $name->getUrl();
} else {
throw new RouteNotFoundException();
}
$type = $this->collector->getDocumentType(get_class($name));
$route = new Route($documentUrl, ['_controller' => $this->routeMap[$type], 'document' => $name, 'type' => $type]);
// the Route has a cache of its own and is not recompiled as long as it does not get modified
$compiledRoute = $route->compile();
$hostTokens = $compiledRoute->getHostTokens();
return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, 'ongr_route', $referenceType, $hostTokens);
} catch (\Exception $e) {
throw new RouteNotFoundException('Document is not correct or route cannot be generated.');
}
}
示例8: testDefaults
public function testDefaults()
{
$route = new Route('/{foo}');
$route->setDefaults(array('foo' => 'bar'));
$this->assertEquals(array('foo' => 'bar'), $route->getDefaults(), '->setDefaults() sets the defaults');
$this->assertEquals($route, $route->setDefaults(array()), '->setDefaults() implements a fluent interface');
$route->setDefault('foo', 'bar');
$this->assertEquals('bar', $route->getDefault('foo'), '->setDefault() sets a default value');
$route->setDefault('foo2', 'bar2');
$this->assertEquals('bar2', $route->getDefault('foo2'), '->getDefault() return the default value');
$this->assertNull($route->getDefault('not_defined'), '->getDefault() return null if default value is not set');
$route->setDefault('_controller', $closure = function () {
return 'Hello';
});
$this->assertEquals($closure, $route->getDefault('_controller'), '->setDefault() sets a default value');
$route->setDefaults(array('foo' => 'foo'));
$route->addDefaults(array('bar' => 'bar'));
$this->assertEquals($route, $route->addDefaults(array()), '->addDefaults() implements a fluent interface');
$this->assertEquals(array('foo' => 'foo', 'bar' => 'bar'), $route->getDefaults(), '->addDefaults() keep previous defaults');
}
示例9: generate
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
try {
$document = $parameters['document'];
if (is_object($document)) {
$documentUrl = $document->url;
} else {
$documentUrl = $document['url'];
}
$type = $this->collector->getDocumentType(get_class($document));
$route = new Route($documentUrl, ['_controller' => $this->routeMap[$type], 'document' => $document, 'type' => $type]);
// the Route has a cache of its own and is not recompiled as long as it does not get modified
$compiledRoute = $route->compile();
$hostTokens = $compiledRoute->getHostTokens();
$debug_message = $this->getRouteDebugMessage($name);
return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $debug_message, $referenceType, $hostTokens);
} catch (\Exception $e) {
throw new RouteNotFoundException('Document is not correct or route cannot be generated.');
}
}
示例10: isAccessedAnonymously
private function isAccessedAnonymously($routeName, Route $route)
{
if (!in_array('GET', $route->getMethods()) && $route->getMethods()) {
return false;
// GET method must be allowed
}
if (strpos($routeName, '_') === 0) {
return false;
// internal|private routes
}
$compiled = $route->compile();
$params = [];
foreach ($compiled->getPathVariables() as $key) {
$params[$key] = 'any';
// we do not care about it
}
foreach ($route->getRequirements() as $key => $regex) {
$params[$key] = 'any';
// we do not care about it
}
foreach ($route->getDefaults() as $key => $default) {
$params[$key] = $default;
}
if (!array_key_exists('_controller', $params)) {
return false;
// route is dynamic, should not be index by robots
}
$uri = $this->get('router')->generate($routeName, $params);
// mock the request
$request = Request::create('http://mock.com' . $uri);
$request->setSession(new Session(new MockFileSessionStorage()));
// run the request through security firewall
$event = new GetResponseEvent($this->getApplication()->getKernel(), $request, HttpKernelInterface::MASTER_REQUEST);
try {
$this->get('security.firewall')->onKernelRequest($event);
} catch (AccessDeniedException $e) {
return false;
// access is denied
}
return !$event->getResponse() instanceof RedirectResponse;
}
示例11: getPathWithoutDefaults
/**
* Returns the path of the route, without placeholders with a default value.
*
* When computing the path outline and fit, we want to skip default-value
* placeholders. If we didn't, the path would never match. Note that this
* only works for placeholders at the end of the path. Infix placeholders
* with default values don't make sense anyway, so that should not be a
* problem.
*
* @param \Symfony\Component\Routing\Route $route
* The route to have the placeholders removed from.
*
* @return string
* The path string, stripped of placeholders that have default values.
*/
public static function getPathWithoutDefaults(Route $route)
{
$path = $route->getPath();
$defaults = $route->getDefaults();
// Remove placeholders with default values from the outline, so that they
// will still match.
$remove = array_map(function ($a) {
return '/{' . $a . '}';
}, array_keys($defaults));
$path = str_replace($remove, '', $path);
return $path;
}
示例12: getAttributes
/**
* Returns an array of values to use as request attributes.
*
* As this method requires the Route object, it is not available
* in matchers that do not have access to the matched Route instance
* (like the PHP and Apache matcher dumpers).
*
* @param Route $route The route we are matching against
* @param string $name The name of the route
* @param array $attributes An array of attributes from the matcher
*
* @return array An array of parameters
*/
protected function getAttributes(Route $route, $name, array $attributes)
{
$attributes['_route'] = $name;
return $this->mergeDefaults($attributes, $route->getDefaults());
}
示例13: compileRoute
//.........这里部分代码省略.........
// GET and HEAD are equivalent
if (in_array('GET', $methods) && !in_array('HEAD', $methods)) {
$methods[] = 'HEAD';
}
}
$supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods));
if (!count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\\^(?P<url>.*?)\\$\\1#', $compiledRoute->getRegex(), $m)) {
if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
$conditions[] = sprintf("rtrim(\$pathinfo, '/') === %s", var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
$hasTrailingSlash = true;
} else {
$conditions[] = sprintf("\$pathinfo === %s", var_export(str_replace('\\', '', $m['url']), true));
}
} else {
if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
$conditions[] = sprintf("0 === strpos(\$pathinfo, %s)", var_export($compiledRoute->getStaticPrefix(), true));
}
$regex = $compiledRoute->getRegex();
if ($supportsTrailingSlash && ($pos = strpos($regex, '/$'))) {
$regex = substr($regex, 0, $pos) . '/?$' . substr($regex, $pos + 2);
$hasTrailingSlash = true;
}
$conditions[] = sprintf("preg_match(%s, \$pathinfo, \$matches)", var_export($regex, true));
$matches = true;
}
if ($compiledRoute->getHostVariables()) {
$hostMatches = true;
}
$conditions = implode(' && ', $conditions);
$code .= <<<EOF
// {$name}
if ({$conditions}) {
EOF;
if ($methods) {
$gotoname = 'not_' . preg_replace('/[^A-Za-z0-9_]/', '', $name);
if (1 === count($methods)) {
$code .= <<<EOF
if (\$this->context->getMethod() != '{$methods['0']}') {
\$allow[] = '{$methods['0']}';
goto {$gotoname};
}
EOF;
} else {
$methods = implode("', '", $methods);
$code .= <<<EOF
if (!in_array(\$this->context->getMethod(), array('{$methods}'))) {
\$allow = array_merge(\$allow, array('{$methods}'));
goto {$gotoname};
}
EOF;
}
}
if ($hasTrailingSlash) {
$code .= <<<EOF
if (substr(\$pathinfo, -1) !== '/') {
return \$this->redirect(\$pathinfo.'/', '{$name}');
}
EOF;
}
if ($scheme = $route->getRequirement('_scheme')) {
if (!$supportsRedirections) {
throw new \LogicException('The "_scheme" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
}
$code .= <<<EOF
if (\$this->context->getScheme() !== '{$scheme}') {
return \$this->redirect(\$pathinfo, '{$name}', '{$scheme}');
}
EOF;
}
// optimize parameters array
if ($matches || $hostMatches) {
$vars = array();
if ($hostMatches) {
$vars[] = '$hostMatches';
}
if ($matches) {
$vars[] = '$matches';
}
$vars[] = "array('_route' => '{$name}')";
$code .= sprintf(" return \$this->mergeDefaults(array_replace(%s), %s);\n", implode(', ', $vars), str_replace("\n", '', var_export($route->getDefaults(), true)));
} elseif ($route->getDefaults()) {
$code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), array('_route' => $name)), true)));
} else {
$code .= sprintf(" return array('_route' => '%s');\n", $name);
}
$code .= " }\n";
if ($methods) {
$code .= " {$gotoname}:\n";
}
return $code;
}
示例14: setRouteOptions
/**
* Set the upcasting route objects.
*
* @param \Symfony\Component\Routing\Route $route
* The route object to add the upcasting information onto.
*/
public function setRouteOptions(Route $route)
{
if ($controller = $this->getControllerClass($route->getDefaults())) {
// Try to use reflection.
if ($this->setParametersFromReflection($controller, $route)) {
return;
}
}
// Try to use _entity_* information on the route.
$this->setParametersFromEntityInformation($route);
}
示例15: testSetRouteOptionsWithEntityAddFormRoute
/**
* Tests setRouteOptions() with an _entity_form route for an add form.
*
* @covers ::setRouteOptions
* @covers ::getControllerClass
* @covers ::getEntityTypes
* @covers ::setParametersFromReflection
* @covers ::setParametersFromEntityInformation
*/
public function testSetRouteOptionsWithEntityAddFormRoute() {
$this->setupEntityTypes();
$route = new Route('/example/add', array(
'_entity_form' => 'entity_test.add',
));
$defaults = $route->getDefaults();
$this->entityResolverManager->setRouteOptions($route);
$this->assertEquals($defaults, $route->getDefaults());
$this->assertFalse($route->hasOption('parameters'));
}