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

ControllerNormalizer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 0
dl 0
loc 46
rs 10
c 0
b 0
f 0

3 Methods

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