Completed
Push — master ( 4d76c2...8242e6 )
by Mikael
02:24
created

ViewCollection::getTemplateFile()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 16
ccs 0
cts 9
cp 0
crap 20
rs 9.7333
c 0
b 0
f 0
1
<?php
2
3
namespace Anax\View;
4
5
use Anax\Commons\ContainerInjectableInterface;
6
use Anax\Commons\ContainerInjectableTrait;
7
8
/**
9
 * A view collection supporting Anax DI, store all views per region,
10
 * render at will.
11
 */
12
class ViewCollection implements
13
    ContainerInjectableInterface
14
{
15
    use ContainerInjectableTrait;
16
17
18
19
    /**
20
     * @var array $views container for all views.
21
     */
22
    private $views = [];
23
24
25
26
    /**
27
     * @var array  $paths  where to look for template files.
28
     * @var string $suffix add to each template file name.
29
     */
30
    private $paths = [];
31
    private $suffix = ".php";
32
33
34
35
    /**
36
     * Set paths to search through when looking for template files.
37
     *
38
     * @param array $paths with directories to search through.
39
     *
40
     * @return self
41
     */
42 1
    public function setPaths(array $paths) : object
43
    {
44 1
        foreach ($paths as $path) {
45 1
            if (!(is_dir($path) && is_readable($path))) {
46 1
                throw new Exception("Directory '$path' is not readable.");
47
            }
48
        }
49 1
        $this->paths = $paths;
50 1
        return $this;
51
    }
52
53
54
55
    /**
56
     * Set suffix to add last to template file givven, as a filename extension.
57
     *
58
     * @param string $suffix to use as file extension.
59
     *
60
     * @return self
61
     */
62 1
    public function setSuffix(string $suffix) : object
63
    {
64 1
        $this->suffix = $suffix;
65 1
        return $this;
66
    }
67
68
69
70
    /**
71
     * Convert template to path to template file and check that it exists.
72
     *
73
     * @param string $template the name of the template file to include
74
     *
75
     * @throws Anax\View\Exception when template file is missing
76
     *
77
     * @return string as path to the template file
78
     */
79
    public function getTemplateFile($template)
80
    {
81
        $file = $template . $this->suffix;
82
        if (is_file($file)) {
83
            return $file;
84
        }
85
86
        foreach ($this->paths as $path) {
87
            $file = $path . "/" . $template . $this->suffix;
88
            if (is_file($file)) {
89
                return $file;
90
            }
91
        }
92
93
        throw new Exception("Could not find template file '$template'.");
94
    }
95
96
97
98
    /**
99
     * Add (create) a view to be included, pass optional data and put the
100
     * view in an optional specific region (default region is "main") and
101
     * pass an optional sort value where the highest value is rendered first.
102
     * The $template can be a:
103
     *  filename (string),
104
     *  callback (array with key callback set to a callable array),
105
     *  view array (key value array with template, data, region, sort)
106
     *
107
     * @param array|string  $template the name of the template file to include.
108
     * @param array         $data     variables to make available to the view,
109
     *                                default is empty.
110
     * @param string        $region   which region to attach the view, default
111
     *                                is "main".
112
     * @param integer       $sort     which order to display the views.
113
     *
114
     * @return self for chaining.
115
     */
116
    public function add(
117
        $template,
118
        array $data = [],
119
        string $region = "main",
120
        int $sort = 0
121
    ) : object {
122
        $view = new View();
123
124
        if (empty($template)) {
125
            $tpl = null;
126
            $type = "empty";
127
        } elseif (is_string($template)) {
128
            $tpl = $this->getTemplateFile($template);
129
            $type = "file";
130
        } elseif (is_array($template)) {
131
            // Can be array with complete view or array with callable callback
132
            $tpl = $template;
133
            $type = "empty";
134
            $region = $tpl["region"] ?? $region;
135
136
            if (isset($tpl["callback"])) {
137
                $tpl["template"] = $template;
138
                $tpl["type"] = "callback";
139
            } elseif (isset($tpl["template"])) {
140
                if (!isset($tpl["type"]) || $tpl["type"] === "file") {
141
                    $tpl["type"] = "file";
142
                    $tpl["template"] = $this->getTemplateFile($tpl["template"]);
143
                }
144
            }
145
        }
146
147
        $view->set($tpl, $data, $sort, $type);
0 ignored issues
show
Bug introduced by
The variable $tpl does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $type does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
It seems like $tpl defined by null on line 125 can also be of type null; however, Anax\View\View::set() does only seem to accept callable, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
148
        $this->views[$region][] = $view;
149
150
        return $this;
151
    }
152
153
154
155
    /**
156
     * Add a callback to be rendered as a view.
157
     *
158
     * @param string $callback function to call to get the content of the view
159
     * @param array  $data     variables to make available to the view, default is empty
160
     * @param string $region   which region to attach the view
161
     * @param int    $sort     which order to display the views
162
     *
163
     * @return $this
164
     */
165 View Code Duplication
    public function addCallback($callback, $data = [], $region = "main", $sort = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
166
    {
167
        $view = new View();
168
        $view->set(["callback" => $callback], $data, $sort, "callback");
169
        $this->views[$region][] = $view;
170
171
        return $this;
172
    }
173
174
175
176
    /**
177
     * Add a string as a view.
178
     *
179
     * @param string $content the content
180
     * @param string $region  which region to attach the view
181
     * @param int    $sort    which order to display the views
182
     *
183
     * @return $this
184
     */
185 View Code Duplication
    public function addString($content, $region = "main", $sort = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
186
    {
187
        $view = new View();
188
        $view->set($content, [], $sort, "string");
189
        $this->views[$region][] = $view;
190
        
191
        return $this;
192
    }
193
194
195
196
    /**
197
     * Check if a region has views to render.
198
     *
199
     * @param string $region which region to check
200
     *
201
     * @return $this
202
     */
203
    public function hasContent($region)
204
    {
205
        return isset($this->views[$region]);
206
    }
207
208
209
210
    /**
211
     * Render all views for a specific region.
212
     *
213
     * @param string $region which region to use
214
     *
215
     * @return void
216
     */
217
    public function render($region = "main")
218
    {
219
        if (!isset($this->views[$region])) {
220
            return $this;
221
        }
222
223
        mergesort($this->views[$region], function ($viewA, $viewB) {
224
            $sortA = $viewA->sortOrder();
225
            $sortB = $viewB->sortOrder();
226
227
            if ($sortA == $sortB) {
228
                return 0;
229
            }
230
231
            return $sortA < $sortB ? -1 : 1;
232
        });
233
234
        foreach ($this->views[$region] as $view) {
235
            $view->render($this->di);
236
        }
237
    }
238
239
240
    /**
241
     * Render all views for a specific region and buffer the result.
242
     *
243
     * @param string $region which region to use.
244
     *
245
     * @return string with the buffered results.
246
     */
247
    public function renderBuffered($region = "main")
248
    {
249
        ob_start();
250
        $this->render($region);
251
        $res = ob_get_contents();
252
        ob_end_clean();
253
        return $res;
254
    }
255
}
256