1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\BladeX; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Illuminate\Contracts\Support\Arrayable; |
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
use Spatie\BladeX\Exceptions\CouldNotRegisterBladeXComponent; |
9
|
|
|
|
10
|
|
|
class BladeXComponent |
11
|
|
|
{ |
12
|
|
|
/** @var string */ |
13
|
|
|
public $bladeViewName; |
14
|
|
|
|
15
|
|
|
/** @var string */ |
16
|
|
|
public $name; |
17
|
|
|
|
18
|
|
|
/** @var string */ |
19
|
|
|
public $viewModel; |
20
|
|
|
|
21
|
|
|
public static function make(string $bladeViewName, string $name = '') |
|
|
|
|
22
|
|
|
{ |
23
|
|
|
return new BladeXComponent($bladeViewName, $name = ''); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function __construct(string $bladeViewName, string $name = '') |
27
|
|
|
{ |
28
|
|
|
$bladeViewName = str_replace('.', '/', $bladeViewName); |
29
|
|
|
|
30
|
|
|
if ($name === '') { |
31
|
|
|
$baseComponentName = explode('/', $bladeViewName); |
32
|
|
|
|
33
|
|
|
$name = kebab_case(end($baseComponentName)); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
if (!view()->exists($bladeViewName)) { |
|
|
|
|
37
|
|
|
throw CouldNotRegisterBladeXComponent::viewNotFound($bladeViewName, $name); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$this->bladeViewName = $bladeViewName; |
41
|
|
|
|
42
|
|
|
$this->name = $name; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param string|\Closure $viewModel |
47
|
|
|
* |
48
|
|
|
* @return $this |
49
|
|
|
*/ |
50
|
|
|
public function viewModel($viewModel) |
51
|
|
|
{ |
52
|
|
|
if (is_callable($viewModel)) { |
53
|
|
|
$this->viewModel = $this->createClosureViewModel($viewModel); |
|
|
|
|
54
|
|
|
|
55
|
|
|
return $this; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if (!class_exists($viewModel)) { |
59
|
|
|
throw CouldNotRegisterBladeXComponent::viewModelNotFound($this->name, $viewModel); |
|
|
|
|
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
if (!is_a($viewModel, Arrayable::class, true)) { |
63
|
|
|
throw CouldNotRegisterBladeXComponent::viewModelNotArrayable($this->name, $viewModel); |
|
|
|
|
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$this->viewModel = $viewModel; |
|
|
|
|
67
|
|
|
|
68
|
|
|
return $this; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
protected function createClosureViewModel(Closure $closure): string |
72
|
|
|
{ |
73
|
|
|
$viewModelClassName = 'bladex.viewModel.'.Str::uuid(); |
74
|
|
|
|
75
|
|
|
app()->bind($viewModelClassName, function ($app, $arguments) use ($closure) { |
76
|
|
|
return (new ClosureViewModel($arguments ?? [])) |
77
|
|
|
->withClosure($closure); |
78
|
|
|
}); |
79
|
|
|
|
80
|
|
|
return $viewModelClassName; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.