Passed
Push — master ( e49144...74d39d )
by Mikael
03:56
created

ViewCollection::hasContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
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
    {
123
        $view = new View();
124
        if (empty($template)) {
125
            $type = "empty";
126
        } elseif (is_string($template)) {
127
            $tpl = $this->getTemplateFile($template);
128
            $type = "file";
129
        } elseif (is_array($template)) {
130
            // Can be array with complete view or array with callable callback
131
            $tpl = $template;
132
            $type = "empty";
133
            $region = $tpl["region"] ?? $region;
134
135
            if (isset($tpl["callback"])) {
136
                $tpl["template"] = $template;
137
                $tpl["type"] = "callback";
138
            } elseif (isset($tpl["template"])) {
139
                if (!isset($tpl["type"]) || $tpl["type"] === "file") {
140
                    $tpl["type"] = "file";
141
                    $tpl["template"] = $this->getTemplateFile($tpl["template"]);
142
                }
143
            }
144
        }
145
146
        $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...
147
        $this->views[$region][] = $view;
148
149
        return $this;
150
    }
151
152
153
154
    /**
155
     * Add a callback to be rendered as a view.
156
     *
157
     * @param string $callback function to call to get the content of the view
158
     * @param array  $data     variables to make available to the view, default is empty
159
     * @param string $region   which region to attach the view
160
     * @param int    $sort     which order to display the views
161
     *
162
     * @return $this
163
     */
164 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...
165
    {
166
        $view = new View();
167
        $view->set(["callback" => $callback], $data, $sort, "callback");
168
        $this->views[$region][] = $view;
169
170
        return $this;
171
    }
172
173
174
175
    /**
176
     * Add a string as a view.
177
     *
178
     * @param string $content the content
179
     * @param string $region  which region to attach the view
180
     * @param int    $sort    which order to display the views
181
     *
182
     * @return $this
183
     */
184 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...
185
    {
186
        $view = new View();
187
        $view->set($content, [], $sort, "string");
188
        $this->views[$region][] = $view;
189
        
190
        return $this;
191
    }
192
193
194
195
    /**
196
     * Check if a region has views to render.
197
     *
198
     * @param string $region which region to check
199
     *
200
     * @return $this
201
     */
202
    public function hasContent($region)
203
    {
204
        return isset($this->views[$region]);
205
    }
206
207
208
209
    /**
210
     * Render all views for a specific region.
211
     *
212
     * @param string $region which region to use
213
     *
214
     * @return void
215
     */
216
    public function render($region = "main")
217
    {
218
        if (!isset($this->views[$region])) {
219
            return $this;
220
        }
221
222
        mergesort($this->views[$region], function ($viewA, $viewB) {
223
            $sortA = $viewA->sortOrder();
224
            $sortB = $viewB->sortOrder();
225
226
            if ($sortA == $sortB) {
227
                return 0;
228
            }
229
230
            return $sortA < $sortB ? -1 : 1;
231
        });
232
233
        foreach ($this->views[$region] as $view) {
234
            $view->render($this->di);
235
        }
236
    }
237
238
239
    /**
240
     * Render all views for a specific region and buffer the result.
241
     *
242
     * @param string $region which region to use.
243
     *
244
     * @return string with the buffered results.
245
     */
246
    public function renderBuffered($region = "main")
247
    {
248
        ob_start();
249
        $this->render($region);
250
        $res = ob_get_contents();
251
        ob_end_clean();
252
        return $res;
253
    }
254
}
255