Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix TwigExtension: Strip basePath from urlFor result #455

Merged
merged 7 commits into from
Jan 17, 2022
39 changes: 22 additions & 17 deletions src/Twig/TwigExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@ class TwigExtension extends AbstractExtension
{
/** @var Router */
private $router;
/** @var string|null */
/** @var string */
private $basePath;
/** @var string */
private $pathPrefix;
/** @var Request */
private $request;

public function __construct(Router $router, Request $request, ?string $pathPrefix)
{
$this->router = $router;
$this->request = $request;
$this->pathPrefix = $pathPrefix;
$this->basePath = $request->getUri()->getBasePath();
$this->pathPrefix = rtrim($this->buildPathPrefix($this->basePath, $pathPrefix), '/');
}

public function getFunctions(): array
Expand Down Expand Up @@ -75,10 +75,14 @@ public function url(string $name, $queryargs = []): string
$query = '?' . http_build_query($queryargs);
}

// this is copy of \Slim\Slim::urlFor()
// to mix path prefix in \Slim\Slim::urlFor
$url = $this->router->urlFor($name);

return rtrim($this->pathPrefix(), '/') . $this->router->urlFor($name) . $query;
// Remove basePath from url
if ($this->basePath && strpos($url, $this->basePath) === 0) {
$url = substr($url, strlen($this->basePath));
}

return $this->pathPrefix(ltrim($url, '/') . $query);
}

/**
Expand All @@ -89,9 +93,7 @@ public function url(string $name, $queryargs = []): string
*/
public function staticUrl(string $path): string
{
$rootUri = $this->pathPrefix();

return rtrim($rootUri, '/') . '/' . $path;
return $this->pathPrefix($path);
}

public function formatBytes($value): string
Expand Down Expand Up @@ -130,20 +132,23 @@ public function formatPercent($value): string
return number_format((float)$value * 100, 0) . ' <span class="units">%</span>';
}

private function pathPrefix(): string
private function pathPrefix($path): string
{
if ($this->pathPrefix !== null) {
return $this->pathPrefix;
}
return $this->pathPrefix . '/' . $path;
}

$rootUri = $this->request->getUri()->getBasePath();
private function buildPathPrefix(string $rootUri, ?string $pathPrefix): string
{
if ($pathPrefix !== null) {
return rtrim($pathPrefix, '/');
}

// Get URL part prepending index.php
$indexPos = strpos($rootUri, 'index.php');
if ($indexPos > 0) {
return substr($rootUri, 0, $indexPos);
}

return $rootUri;
return rtrim($rootUri, '/');
}
}