1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\BladeX; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\File; |
6
|
|
|
use Spatie\BladeX\Exceptions\CouldNotRegisterComponent; |
7
|
|
|
use Symfony\Component\Finder\SplFileInfo; |
8
|
|
|
use Symfony\Component\DomCrawler\Crawler; |
9
|
|
|
|
10
|
|
|
class BladeX |
11
|
|
|
{ |
12
|
|
|
/** @var array */ |
13
|
|
|
public $registeredComponents = []; |
14
|
|
|
|
15
|
|
|
public function component(string $componentName, string $viewName) |
16
|
|
|
{ |
17
|
|
|
if (! view()->exists($viewName)) { |
|
|
|
|
18
|
|
|
throw CouldNotRegisterComponent::viewNotFound($componentName, $viewName); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
$this->registeredComponents[$componentName] = $viewName; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function components(string $directory) |
25
|
|
|
{ |
26
|
|
|
collect(File::allFiles($directory)) |
27
|
|
|
->filter(function (SplFileInfo $file) { |
28
|
|
|
return ends_with($file->getFilename(), '.blade.php'); |
29
|
|
|
}) |
30
|
|
|
|
31
|
|
|
->each(function(SplFileInfo $fileInfo) { |
32
|
|
|
$componentName = rtrim($fileInfo->getFilename(), '.blade.php'); |
33
|
|
|
|
34
|
|
|
$viewName = $this->getViewName($fileInfo->getPathname()); |
35
|
|
|
|
36
|
|
|
dd($componentName, $viewName); |
37
|
|
|
}); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
private function getViewName(string $pathName): string |
41
|
|
|
{ |
42
|
|
|
foreach (app('view.finder')->getPaths() as $registeredViewPath) { |
43
|
|
|
dump('foreach', $pathName, realpath($registeredViewPath), '---'); |
44
|
|
|
$pathName = str_replace(realpath($registeredViewPath), '', $pathName); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return $pathName; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function compile(string $view): string |
51
|
|
|
{ |
52
|
|
|
$crawler = new Crawler($view); |
53
|
|
|
|
54
|
|
|
foreach($this->registeredComponents as $componentName => $classOrView) { |
55
|
|
|
$crawler |
56
|
|
|
->filter($componentName) |
57
|
|
|
->each(function (Crawler $subCrawler) use ($classOrView) { |
58
|
|
|
$node = $subCrawler->getNode(0); |
59
|
|
|
|
60
|
|
|
$node->parentNode->replaceChild( |
61
|
|
|
$node->ownerDocument->createTextNode("@include({$classOrView})"), // TEMP: @include everything |
62
|
|
|
$node |
63
|
|
|
); |
64
|
|
|
}); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $crawler->html(); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
It seems like the method you are trying to call exists only in some of the possible types.
Let’s take a look at an example:
Available Fixes
Add an additional type-check:
Only allow a single type to be passed if the variable comes from a parameter: