Completed
Push — master ( 4f0406...3f0c83 )
by Iman
107:14 queued 51:28
created

ControllerNormalizer::determineDataMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
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 $widget
10
     * @return null
11
     */
12
    public function normalizeControllerMethod($widget)
13
    {
14
        list($controllerMethod, $ctrlClass) = $this->determineDataMethod($widget);
15
16
        $this->checkControllerExists($ctrlClass);
17
        $this->checkDataMethodExists($ctrlClass);
18
19
        $widget->controller = $controllerMethod;
20
    }
21
22
    /**
23
     * @param $ctrlClass
24
     */
25
    private function checkControllerExists($ctrlClass)
26
    {
27
        if (! class_exists($ctrlClass)) {
28
            throw new \InvalidArgumentException("Controller class: [{$ctrlClass}] not found.");
29
        }
30
    }
31
32
    /**
33
     * @param $ctrlClass
34
     */
35
    private function checkDataMethodExists($ctrlClass)
36
    {
37
        if (! method_exists($ctrlClass, 'data')) {
38
            throw new \InvalidArgumentException("'data' method not found on ".$ctrlClass);
39
        }
40
    }
41
42
    /**
43
     * @param $widget
44
     * @return array
45
     */
46
    private function determineDataMethod($widget)
47
    {
48
// We decide to call data method on widget object by default.
49
        $controllerMethod = [$widget, 'data'];
50
        $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
        if (property_exists($widget, 'controller')) {
55
            $ctrlClass = $widget->controller;
56
            $controllerMethod = ($ctrlClass) . '@data';
57
        }
58
        return array($controllerMethod, $ctrlClass);
59
    }
60
}
61