1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Imanghafoori\Widgets\Utils\Normalizers; |
4
|
|
|
|
5
|
|
|
use Imanghafoori\Widgets\Utils\NormalizerContract; |
6
|
|
|
|
7
|
|
|
class ControllerNormalizer implements NormalizerContract |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Figures out which method should be called as the controller. |
11
|
|
|
* @param object $widget |
12
|
|
|
* @return void |
13
|
|
|
*/ |
14
|
22 |
|
public function normalize($widget): void |
15
|
|
|
{ |
16
|
22 |
|
[$controllerMethod, $ctrlClass] = $this->determineDataMethod($widget); |
17
|
|
|
|
18
|
22 |
|
$this->checkControllerExists($ctrlClass); |
19
|
22 |
|
$this->checkDataMethodExists($controllerMethod); |
20
|
|
|
|
21
|
22 |
|
$widget->controller = $controllerMethod; |
22
|
22 |
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param string $ctrlClass |
26
|
|
|
*/ |
27
|
22 |
|
private function checkControllerExists(string $ctrlClass): void |
28
|
|
|
{ |
29
|
22 |
|
if (! class_exists($ctrlClass)) { |
30
|
|
|
throw new \InvalidArgumentException("Controller class: [{$ctrlClass}] not found."); |
31
|
|
|
} |
32
|
22 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param $ctrlClass |
36
|
|
|
*/ |
37
|
22 |
|
private function checkDataMethodExists($ctrlClass): void |
38
|
|
|
{ |
39
|
22 |
|
if (is_string($ctrlClass)) { |
40
|
3 |
|
$ctrlClass = explode('@', $ctrlClass); |
41
|
|
|
} |
42
|
|
|
|
43
|
22 |
|
[$ctrlClass, $method] = $ctrlClass; |
44
|
22 |
|
if (! method_exists($ctrlClass, $method)) { |
45
|
|
|
throw new \InvalidArgumentException("'data' method not found on ".$ctrlClass); |
46
|
|
|
} |
47
|
22 |
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param object $widget |
51
|
|
|
* @return array [$controllerMethod, $ctrlClass] |
52
|
|
|
*/ |
53
|
22 |
|
private function determineDataMethod($widget): array |
54
|
|
|
{ |
55
|
|
|
// We decide to call data method on widget object by default. |
56
|
|
|
// If the user has explicitly declared controller class path on widget |
57
|
|
|
// then we decide to call data method on that instead. |
58
|
22 |
|
if (! property_exists($widget, 'controller')) { |
59
|
19 |
|
return [[$widget, 'data'], get_class($widget)]; |
60
|
|
|
} |
61
|
|
|
|
62
|
3 |
|
if (is_string($widget->controller)) { |
63
|
2 |
|
if (! str_contains($widget->controller, '@')) { |
64
|
1 |
|
return [$widget->controller.'@data', $widget->controller]; |
65
|
|
|
} |
66
|
1 |
|
$widget->controller = explode('@', $widget->controller); |
67
|
|
|
} |
68
|
|
|
|
69
|
2 |
|
$ctrlClass = $widget->controller[0]; |
70
|
2 |
|
$controllerMethod = implode('@', $widget->controller); |
71
|
|
|
|
72
|
2 |
|
return [$controllerMethod, $ctrlClass]; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|