Passed
Push — master ( 2f2795...71165f )
by Iman
06:01
created

ControllerNormalizer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Test Coverage

Coverage 90.48%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 55
ccs 19
cts 21
cp 0.9048
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

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