Skip to content
Merged
Show file tree
Hide file tree
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
24 changes: 21 additions & 3 deletions src/Phaseolies/Error/Utils/PathResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,36 @@ class PathResolver
*/
public static function toDisplayPath(string $absoluteFile): string
{
$absoluteFile = self::normalizePath($absoluteFile);
$match = self::matchPsr4Prefix($absoluteFile);

if ($match === null) {
return str_replace(base_path() . '/', '', $absoluteFile);
$basePath = rtrim(self::normalizePath(base_path()), '/');

return str_starts_with($absoluteFile, $basePath . '/')
? substr($absoluteFile, strlen($basePath) + 1)
: $absoluteFile;
}

[$prefix, $directory] = $match;

$relative = substr($absoluteFile, strlen($directory));
$namespacePath = str_replace('\\', '/', rtrim($prefix, '\\'));
$namespacePath = rtrim(self::normalizePath($prefix), '/');

return $namespacePath . '/' . ltrim($relative, '/');
}

/**
* Normalize filesystem separators for display-path comparisons.
*
* @param string $path
* @return string
*/
private static function normalizePath(string $path): string
{
return str_replace('\\', '/', $path);
}

/**
* Find the longest matching PSR-4 directory for the given file.
*
Expand All @@ -51,9 +67,11 @@ private static function matchPsr4Prefix(string $absoluteFile): ?array
$bestPrefix = null;
$bestDirectory = null;

$absoluteFile = self::normalizePath($absoluteFile);

foreach ($map as $prefix => $directories) {
foreach ($directories as $directory) {
$directory = rtrim($directory, '/') . '/';
$directory = rtrim(self::normalizePath($directory), '/') . '/';

if (
str_starts_with($absoluteFile, $directory)
Expand Down
38 changes: 38 additions & 0 deletions tests/Error/CrossPlatformErrorPageTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Tests\Unit\Error;

require_once __DIR__ . '/../Support/MockContainer.php';

use Phaseolies\DI\Container;
use Phaseolies\Error\Utils\PathResolver;
use PHPUnit\Framework\TestCase;
use Tests\Support\MockContainer;

class CrossPlatformErrorPageTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();

$container = new MockContainer();
$basePath = (new \ReflectionClass($container))->getProperty('basePath');
$basePath->setValue($container, dirname(__DIR__, 2));

Container::setInstance($container);
}

public function testErrorFilePathIsDisplayedRelativeToTheApplicationRoot(): void
{
$errorFile = base_path(
'storage'
. DIRECTORY_SEPARATOR . 'framework'
. DIRECTORY_SEPARATOR . 'views'
. DIRECTORY_SEPARATOR . 'error.php'
);

$displayPath = PathResolver::toDisplayPath($errorFile);

$this->assertSame('storage/framework/views/error.php', $displayPath);
}
}
Loading