-
-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathSpotlight.php
More file actions
90 lines (73 loc) · 2.7 KB
/
Spotlight.php
File metadata and controls
90 lines (73 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace LivewireUI\Spotlight;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Str;
use Livewire\Component;
use Livewire\ImplicitlyBoundMethod;
class Spotlight extends Component
{
public static array $commands = [];
public array $dependencyQueryResults = [];
public static function registerCommand(string $command): void
{
tap(new $command, function (SpotlightCommand $command) {
self::$commands[] = $command;
});
}
public static function registerCommandIf(bool $condition, string $command): void
{
if ($condition === false) {
return;
}
self::registerCommand($command);
}
public static function registerCommandUnless(bool $condition, string $command): void
{
if ($condition === true) {
return;
}
self::registerCommand($command);
}
protected function getCommandById(string $id): ?SpotlightCommand
{
return collect(self::$commands)->first(function ($command) use ($id) {
return $command->getId() === $id;
});
}
public function searchDependency(string $commandId, $dependency, $query, $resolvedDependencies = []): void
{
$command = $this->getCommandById($commandId);
$method = Str::camel('search ' . $dependency);
if (is_object($command) and method_exists($command, $method)) {
$params = array_merge(['query' => $query], (array) $resolvedDependencies);
$this->dependencyQueryResults = collect(ImplicitlyBoundMethod::call(app(), [$command, $method], $params))
->map(fn (SpotlightSearchResult $result) => $result->toArray())
->toArray();
}
}
public function execute(string $commandId, array $dependencies = []): void
{
$command = $this->getCommandById($commandId);
if (method_exists($command, 'execute')) {
$params = array_merge(['spotlight' => $this], $dependencies);
/**
* @psalm-suppress InvalidArgument
*/
ImplicitlyBoundMethod::call(app(), [$command, 'execute'], $params);
}
}
public function render(): View | Factory
{
return view('livewire-ui-spotlight::spotlight', [
'commands' => collect(self::$commands)->map(function (SpotlightCommand $command) {
return [
'id' => $command->getId(),
'name' => $command->getName(),
'description' => $command->getDescription(),
'dependencies' => $command->dependencies()?->toArray() ?? [],
];
}),
]);
}
}