88use Dom \NodeList ;
99use Exception ;
1010use Tempest \Core \Kernel ;
11+ use Tempest \Discovery \DiscoveryLocation ;
12+ use Tempest \Mapper \Exceptions \ViewNotFound ;
1113use Tempest \View \Attributes \AttributeFactory ;
1214use Tempest \View \Element ;
1315use Tempest \View \Elements \ElementFactory ;
16+ use Tempest \View \View ;
1417use function Tempest \path ;
18+ use function Tempest \Support \arr ;
1519use function Tempest \Support \str ;
1620use const Dom \HTML_NO_DEFAULT_NS ;
1721
@@ -35,12 +39,12 @@ public function __construct(
3539 private Kernel $ kernel ,
3640 ) {}
3741
38- public function compile (string $ path ): string
42+ public function compile (string | View $ view ): string
3943 {
4044 $ this ->elementFactory ->setViewCompiler ($ this );
4145
4246 // 1. Retrieve template
43- $ template = $ this ->retrieveTemplate ($ path );
47+ $ template = $ this ->retrieveTemplate ($ view );
4448
4549 // 2. Parse as DOM
4650 $ dom = $ this ->parseDom ($ template );
@@ -57,23 +61,38 @@ public function compile(string $path): string
5761 return $ compiled ;
5862 }
5963
60- private function retrieveTemplate (string $ path ): string
64+ private function retrieveTemplate (string | View $ view ): string
6165 {
66+ $ path = $ view instanceof View ? $ view ->path : $ view ;
67+
6268 if (! str_ends_with ($ path , '.php ' )) {
6369 return $ path ;
6470 }
6571
66- $ discoveryLocations = $ this ->kernel ->discoveryLocations ;
72+ $ searchPathOptions = [
73+ $ path
74+ ];
6775
68- $ searchPath = $ path ;
76+ if ($ view instanceof View && $ view ->relativeRootPath !== null ) {
77+ $ searchPathOptions [] = path ($ view ->relativeRootPath , $ path )->toString ();
78+ }
6979
70- while (! file_exists ($ searchPath ) && $ location = current ($ discoveryLocations )) {
71- $ searchPath = path ($ location ->path , $ path )->toString ();
72- next ($ discoveryLocations );
80+ $ searchPathOptions = [
81+ ...$ searchPathOptions ,
82+ ...arr ($ this ->kernel ->discoveryLocations )
83+ ->map (fn (DiscoveryLocation $ discoveryLocation ) => path ($ discoveryLocation ->path , $ path )->toString ())
84+ ->toArray ()
85+ ];
86+
87+ foreach ($ searchPathOptions as $ searchPath )
88+ {
89+ if (file_exists ($ searchPath )) {
90+ break ;
91+ }
7392 }
7493
7594 if (! file_exists ($ searchPath )) {
76- throw new Exception ( " View { $ searchPath } not found " );
95+ throw new ViewNotFound ( $ path );
7796 }
7897
7998 return file_get_contents ($ searchPath );
0 commit comments