Completed
Push — master ( 2c7ea9...284ef7 )
by Iman
01:59
created

Normalizer::normalizeControllerMethod()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 9
Ratio 47.37 %

Importance

Changes 0
Metric Value
dl 9
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 0
1
<?php
2
3
namespace Imanghafoori\Widgets\Utils;
4
5
6
use Imanghafoori\Widgets\BaseWidget;
7
8
class Normalizer
9
{
10
    private $widget;
11
12
    public function normalizeWidgetConfig(BaseWidget $widget)
13
    {
14
        $this->widget = $widget;
15
        $this->normalizeControllerMethod();
16
        $this->normalizePresenterName();
17
        $this->normalizeTemplateName();
18
        $this->normalizeContextAs();
19
        $this->normalizeCacheLifeTime();
20
        $this->normalizeCacheTags();
21
    }
22
23
    /**
24
     * Figures out which method should be called as the controller.
25
     * @return null
26
     */
27
    private function normalizeControllerMethod()
28
    {
29
        // If the user has explicitly declared controller class path on the sub-class
30
        if ($this->widget->controller === null) {
31
            if (!method_exists($this->widget, 'data')) {
32
                throw new \BadMethodCallException("'data' method not found on " . class_basename($this->widget));
33
            }
34
            // We decide to call data method on widget object.
35
            $this->widget->controller = [$this->widget, 'data'];
36 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
37
            // If the user has specified the controller class path
38
            if (!class_exists($this->widget->controller)) {
39
                throw new \InvalidArgumentException("Controller class: [{$this->widget->controller}] not found.");
40
            }
41
42
            // we decide to call data method on that.
43
            $this->widget->controller = ($this->widget->controller) . '@data';
44
        }
45
    }
46
47
    /**
48
     * Figures out which method should be called as the presenter
49
     * @return null
50
     */
51
    private function normalizePresenterName()
52
    {
53
        if ($this->widget->presenter === 'default') {
54
            $presenter = class_basename($this->widget) . 'Presenter';
55
56
            if (class_exists($presenter)) {
57
                $this->widget->presenter = $presenter . '@presenter';
58
            } else {
59
                $this->widget->presenter = null;
60
            }
61 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
62
            if (class_exists($this->widget->presenter) === false) {
63
                throw new \InvalidArgumentException("Presenter Class [{$this->widget->presenter}] not found.");
64
            }
65
            $this->widget->presenter = $this->widget->presenter . '@present';
66
        }
67
68
    }
69
70
    /**
71
     * Figures out which template to render.
72
     * @return null
73
     */
74
    private function normalizeTemplateName()
75
    {
76
        // class name without namespace.
77
        $className = str_replace('App\\Widgets\\', '', class_basename($this->widget));
78
        // replace slashes with dots
79
        $className = str_replace(['\\', '/'], '.', $className);
80
81
        if ($this->widget->template === null) {
82
            $this->widget->template = 'Widgets::' . $className . 'View';
83
        }
84
85
        if (!view()->exists($this->widget->template)) {
0 ignored issues
show
Bug introduced by
The method exists does only exist in Illuminate\Contracts\View\Factory, but not in Illuminate\View\View.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
86
            throw new \InvalidArgumentException("View file [{$className}View] not found by: '" . class_basename($this->widget) . " '");
87
        }
88
    }
89
90
    /**
91
     * Figures out what the variable name should be in view file.
92
     * @return null
93
     */
94
    private function normalizeContextAs()
95
    {
96
        // removes the $ sign.
97
        $this->widget->contextAs = str_replace('$', '', (string)$this->widget->contextAs);
98
    }
99
100
    /**
101
     * ّFigures out how long the cache life time should be.
102
     * @return null
103
     */
104
    private function normalizeCacheLifeTime()
105
    {
106
        if ($this->widget->cacheLifeTime === 'env_default') {
107
            $this->widget->cacheLifeTime = (int)(env('WIDGET_DEFAULT_CACHE_LIFETIME', 0));
0 ignored issues
show
Documentation Bug introduced by
The property $cacheLifeTime was declared of type string, but (int) env('WIDGET_DEFAULT_CACHE_LIFETIME', 0) is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
108
        }
109
110
        if ($this->widget->cacheLifeTime === 'forever') {
111
            $this->widget->cacheLifeTime = -1;
0 ignored issues
show
Documentation Bug introduced by
The property $cacheLifeTime was declared of type string, but -1 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
112
        }
113
114
    }
115
116
    /**
117
     * ّFigures out what the cache tags should be.
118
     * @return null
119
     */
120
    private function normalizeCacheTags()
121
    {
122
        if ($this->cacheShouldBeTagged()) {
123
            if (is_string($this->widget->cacheTags)) {
124
                $this->widget->cacheTags = [$this->widget->cacheTags];
125
            }
126
127
            if (!is_array($this->widget->cacheTags)) {
128
                throw new \InvalidArgumentException('Cache Tags should be of type String or Array.');
129
            }
130
        }
131
    }
132
    /**
133
     * Determine whether cache tags should be applied or not
134
     * @return bool
135
     */
136
    private function cacheShouldBeTagged()
137
    {
138
        return !in_array(env('CACHE_DRIVER', 'file'), ['file', 'database']) and $this->widget->cacheTags;
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
139
    }
140
141
}