Passed
Push — master ( 436057...7b94bf )
by Iman
02:27
created

ControllerNormalizer::determineDataMethod()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 1
dl 0
loc 20
ccs 10
cts 10
cp 1
crap 4
rs 9.9666
c 0
b 0
f 0
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($ctrlClass);
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(string $ctrlClass): void
38
    {
39 22
        if (! method_exists($ctrlClass, 'data')) {
40
            throw new \InvalidArgumentException("'data' method not found on ".$ctrlClass);
41
        }
42 22
    }
43
44
    /**
45
     * @param object $widget
46
     * @return array [$controllerMethod, $ctrlClass]
47
     */
48 22
    private function determineDataMethod($widget): array
49
    {
50
        // We decide to call data method on widget object by default.
51
        // If the user has explicitly declared controller class path on widget
52
        // then we decide to call data method on that instead.
53 22
        if (! property_exists($widget, 'controller')) {
54 19
            return [[$widget, 'data'], get_class($widget)];
55
        }
56
57 3
        if (is_string($widget->controller)) {
58 2
            if (! str_contains($widget->controller, '@')) {
59 1
                return [$widget->controller.'@data', $widget->controller];
60
            }
61 1
            $widget->controller = explode('@', $widget->controller);
62
        }
63
64 2
        $ctrlClass = $widget->controller[0];
65 2
        $controllerMethod = implode('@', $widget->controller);
66
67 2
        return [$controllerMethod, $ctrlClass];
68
    }
69
}
70