Completed
Push — master ( fbc7c8...750795 )
by Iman
02:06
created

ControllerNormalizer::normalizeControllerMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 1
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
        // We decide to call data method on widget object by default.
15
        $controllerMethod = [$widget, 'data'];
16
        $ctrlClass = get_class($widget);
17
18
        // If the user has explicitly declared controller class path on widget
19
        // then we decide to call data method on that instead.
20
        if ($widget->controller) {
21
            $ctrlClass = $widget->controller;
22
            $controllerMethod = ($ctrlClass) . '@data';
23
        }
24
25
        $this->checkControllerExists($ctrlClass);
26
        $this->checkDataMethodExists($ctrlClass);
27
28
        $widget->controller = $controllerMethod;
29
    }
30
31
    /**
32
     * @param $ctrlClass
33
     */
34
    private function checkControllerExists($ctrlClass)
35
    {
36
        if (!class_exists($ctrlClass)) {
37
            throw new \InvalidArgumentException("Controller class: [{$ctrlClass}] not found.");
38
        }
39
    }
40
41
    /**
42
     * @param $ctrlClass
43
     */
44
    private function checkDataMethodExists($ctrlClass)
45
    {
46
        if (!method_exists($ctrlClass, 'data')) {
47
            throw new \InvalidArgumentException("'data' method not found on " . $ctrlClass);
48
        }
49
    }
50
}
51