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

ControllerNormalizer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 10
c 0
b 0
f 0
wmc 7
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A normalizeControllerMethod() 0 9 1
A checkControllerExists() 0 6 2
A checkDataMethodExists() 0 6 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 $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