Completed
Push — master ( f490f2...85ca6a )
by Freek
01:42
created

BladeX::components()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Spatie\BladeX;
4
5
use Illuminate\Support\Facades\File;
6
use Spatie\BladeX\Exceptions\CouldNotRegisterComponent;
7
<<<<<<< HEAD
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_SL
Loading history...
8
use Symfony\Component\Finder\SplFileInfo;
9
=======
10
use Symfony\Component\DomCrawler\Crawler;
11
>>>>>>> f490f238acb8e8fa9295d33f2f52f91948a5df34
12
13
class BladeX
14
{
15
    /** @var array */
16
    public $registeredComponents = [];
17
18
    public function component(string $componentName, string $viewName)
19
    {
20
        if (! view()->exists($viewName)) {
21
            throw CouldNotRegisterComponent::viewNotFound($componentName, $viewName);
22
        }
23
24
        $this->registeredComponents[$componentName] = $viewName;
25
    }
26
27
    public function components(string $directory)
28
    {
29
        collect(File::allFiles($directory))
30
            ->filter(function (SplFileInfo $file) {
31
                return ends_with($file->getFilename(), '.blade.php');
32
            })
33
34
            ->each(function(SplFileInfo $fileInfo) {
35
                $componentName = rtrim($fileInfo->getFilename(), '.blade.php');
36
37
                $viewName = $this->getViewName($fileInfo->getPathname());
38
39
                dd($componentName, $viewName);
40
            });
41
    }
42
43
    private function getViewName(string $pathName): string
44
    {
45
        foreach (app('view.finder')->getPaths() as $registeredViewPath) {
46
            dump('foreach', $pathName, realpath($registeredViewPath), '---');
47
            $pathName = str_replace(realpath($registeredViewPath), '', $pathName);
48
        }
49
50
        return $pathName;
51
    }
52
53
    public function compile(string $view): string
54
    {
55
        $crawler = new Crawler($view);
56
57
        foreach($this->registeredComponents as $componentName => $classOrView) {
58
            $crawler
59
                ->filter($componentName)
60
                ->each(function (Crawler $subCrawler) use ($classOrView) {
61
                    $node = $subCrawler->getNode(0);
62
63
                    $node->parentNode->replaceChild(
64
                        $node->ownerDocument->createTextNode("@include({$classOrView})"), // TEMP: @include everything
65
                        $node
66
                    );
67
                });
68
        }
69
70
        return $crawler->html();
71
    }
72
}
73