/** * Get the relative URL for a given route name. * * @param string $route * @param array $params * @param array $query * * @return string */ public function uriFor($route, array $params = [], array $query = []) { if (!$route) { return ''; } return $this->router->relativePathFor($route, $params, $query); }
/** * Base path is ignored by relativePathFor() * */ public function testRelativePathFor() { $this->router->setBasePath('/base/path'); $methods = ['GET']; $pattern = '/hello/{first:\\w+}/{last}'; $callable = function ($request, $response, $args) { echo sprintf('Hello %s %s', $args['first'], $args['last']); }; $route = $this->router->map($methods, $pattern, $callable); $route->setName('foo'); $this->assertEquals('/hello/josh/lockhart', $this->router->relativePathFor('foo', ['first' => 'josh', 'last' => 'lockhart'])); }
/** * {@inheritdoc} */ public function relativePathFor($name, array $data = [], array $queryParams = [], $lang = null) { if (!$name) { throw new InvalidArgumentException("Invalid empty data path name"); } // Get values needed for localized paths $identifier = $this->getLanguageIdentifier(); $locales = $this->getLocalization(); // Return default behavior if no localized path is applicable if (!$identifier || !$locales) { return parent::relativePathFor($name, $data, $queryParams); } // determine locale to use for path $locale = $locales->getActive(); $lang = $lang ?: $data[$identifier] ?? null; if ($lang) { $locale = $locales->find($lang); if (!$locale) { throw new InvalidArgumentException(sprintf("Invalid data '%s' for URL argument '%s'", $lang, $identifier)); } } // Set language identifier for path // Note: Add slash as prefix as this is normally part of the identifier (in optional language mode) $data[$identifier] = '/' . $locale->getLanguage(); $path = parent::relativePathFor($name, $data, $queryParams); // Cut out localization part (identifier) for default language if wanted if ($this->isOmitDefaultLanguage() && $locale == $locales->getDefault()) { $path = preg_replace('/\\/' . $locale->getLanguage() . '(\\/|$)/', '/', $path); } // Sanitize url (remove prior set slash) if duplicate $path = str_replace('//', '/', $path); return $path; }