Skip to content
Closed
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
45 changes: 25 additions & 20 deletions src/LayerResolver/Resolvers/NamespaceLayerResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use function str_starts_with;
use function strlen;
use function usort;

/**
* Resolves a layer by matching the file path against registered layer paths.
Expand All @@ -22,53 +23,57 @@
/**
* Layer paths stored with a trailing '/' so a single str_starts_with()
* against the file path (also suffixed with '/') covers both exact and
* descendant matches.
* descendant matches. Kept in declaration order for resolveAll().
*
* @var array<string, list<string>>
*/
private array $normalisedLayers;

/**
* The same paths flattened and sorted longest first, so resolve() can
* return on the first match: it is always the most specific layer.
* Equal lengths keep declaration order.
*
* @var list<array{0: string, 1: string}> [layerPath, layerName]
*/
private array $layerPathsLongestFirst;

/**
* @param array<string, string|list<string>> $layers Map of layer name → path prefixes
*/
public function __construct(
array $layers,
string $basePath,
) {
$normalisedLayers = [];
$normalisedLayers = [];
$layerPathsLongestFirst = [];

foreach ($layers as $layerName => $layerPaths) {
foreach ((array) $layerPaths as $layerPath) {
$normalisedLayers[$layerName][] = Path::normalise(
Path::resolve($layerPath, $basePath),
canonicalise: true
) . '/';
$normalisedPath = Path::normalise(Path::resolve($layerPath, $basePath), canonicalise: true) . '/';

$normalisedLayers[$layerName][] = $normalisedPath;
$layerPathsLongestFirst[] = [$normalisedPath, $layerName];
}
}

$this->normalisedLayers = $normalisedLayers;
usort($layerPathsLongestFirst, static fn (array $a, array $b): int => strlen($b[0]) <=> strlen($a[0]));

$this->normalisedLayers = $normalisedLayers;
$this->layerPathsLongestFirst = $layerPathsLongestFirst;
}

public function resolve(string $className, string $filePath): ?string
{
$pathWithSlash = Path::normalise($filePath, canonicalise: true) . '/';
$matchedLayer = null;
$matchedLength = -1;

foreach ($this->normalisedLayers as $layerName => $layerPaths) {
foreach ($layerPaths as $layerPath) {
if (str_starts_with($pathWithSlash, $layerPath)) {
$length = strlen($layerPath);

if ($length > $matchedLength) {
$matchedLayer = $layerName;
$matchedLength = $length;
}
}
foreach ($this->layerPathsLongestFirst as [$layerPath, $layerName]) {
if (str_starts_with($pathWithSlash, $layerPath)) {
return $layerName;
}
}

return $matchedLayer;
return null;
}

/**
Expand Down