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

TemplateNormalizer::normalizeTemplateName()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 4
nop 1
1
<?php
2
3
namespace Imanghafoori\Widgets\Utils\Normalizers;
4
5
class TemplateNormalizer
6
{
7
    /**
8
     * Figures out which template to render.
9
     * @param $widget
10
     * @return null
11
     */
12
    public function normalizeTemplateName($widget)
13
    {
14
        // class name without namespace.
15
        $className = str_replace('App\\Widgets\\', '', class_basename($widget));
16
17
        // replace slashes with dots
18
        $className = str_replace(['\\', '/'], '.', $className);
19
20
        if ($widget->template === null) {
21
            $widget->template = 'Widgets::' . $className . 'View';
22
        }
23
24
        if (!view()->exists($widget->template)) {
1 ignored issue
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...
25
            throw new \InvalidArgumentException("View file [{$className}View] not found by: '" . class_basename($widget) . " '");
26
        }
27
    }
28
}
29