Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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, '/');
}
}