Completed
Push — master ( c774b0...253d46 )
by Mikael
02:22
created

ViewContainer::renderBuffered()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 6
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Anax\View;
4
5
/**
6
 * A view container, store all views per region, render at will.
7
 */
8
class ViewContainer implements
9
    \Anax\Common\ConfigureInterface,
10
    \Anax\Common\AppInjectableInterface
11
{
12
    use \Anax\Common\ConfigureTrait,
13
        \Anax\Common\AppInjectableTrait;
14
15
16
17
    /** @var [] $views Array for all views. */
0 ignored issues
show
Documentation introduced by
The doc-type [] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
18
    private $views = [];
19
20
21
22
    /**
23
     * Convert template to path to template file.
24
     *
25
     * @param string $template the name of the template file to include
26
     *
27
     * @throws Anax\View\Exception when template file is missing
28
     *
29
     * @return string as path to the template file
30
     */
31
    public function getTemplateFile($template)
32
    {
33
        $paths  = $this->config["path"];
34
        $suffix = $this->config["suffix"];
35
36
        foreach ($paths as $path) {
37
            $file = $path . "/" . $template . $suffix;
38
            if (is_file($file)) {
39
                return $file;
40
            }
41
        }
42
43
        throw new Exception("Could not find template file '$template'.");
44
    }
45
46
47
48
    /**
49
     * Add (create) a view to be included, pass optional data and put the
50
     * view in an optional specific region (default region is "main") and
51
     * pass an optional sort value where the highest value is rendered first.
52
     * The $template can be a:
53
     *  filename (string),
54
     *  callback (array with key callback set to a callable array),
55
     *  view array (key value array with template, data, region, sort)
56
     *
57
     * @param string  $template the name of the template file to include.
58
     * @param array   $data     variables to make available to the view,
59
     *                          default is empty.
60
     * @param string  $region   which region to attach the view, default is
61
     *                          "main".
62
     * @param integer $sort     which order to display the views.
63
     *
64
     * @return self for chaining.
65
     */
66
    public function add($template, $data = [], $region = "main", $sort = 0)
67
    {
68
        if (empty($template)) {
69
            return $this;
70
        }
71
72
        $view = new View();
73
74
        if (is_string($template)) {
75
            $tpl = $this->getTemplateFile($template);
76
            $type = "file";
77
        } elseif (is_array($template)) {
78
            // Can be array with complete view or array with callable callback
79
            $tpl = $template;
80
            $type = null;
81
            $region = isset($tpl["region"])
82
                ? $tpl["region"]
83
                : $region;
84
85
            if (isset($tpl["callback"])) {
86
                $tpl["template"] = $template;
87
                $tpl["type"] = "callback";
88
            } elseif (isset($tpl["template"])) {
89
                if (!isset($tpl["type"]) || $tpl["type"] === "file") {
90
                    $tpl["type"] = "file";
91
                    $tpl["template"] = $this->getTemplateFile($tpl["template"]);
92
                }
93
            }
94
        }
95
96
        $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...
97
        $this->views[$region][] = $view;
98
99
        return $this;
100
    }
101
102
103
104
    /**
105
     * Add a callback to be rendered as a view.
106
     *
107
     * @param string $callback function to call to get the content of the view
108
     * @param array  $data     variables to make available to the view, default is empty
109
     * @param string $region   which region to attach the view
110
     * @param int    $sort     which order to display the views
111
     *
112
     * @return $this
113
     */
114 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...
115
    {
116
        $view = new View();
117
        $view->set(["callback" => $callback], $data, $sort, "callback");
118
        $this->views[$region][] = $view;
119
120
        return $this;
121
    }
122
123
124
125
    /**
126
     * Add a string as a view.
127
     *
128
     * @param string $content the content
129
     * @param string $region  which region to attach the view
130
     * @param int    $sort    which order to display the views
131
     *
132
     * @return $this
133
     */
134 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...
135
    {
136
        $view = new View();
137
        $view->set($content, [], $sort, "string");
138
        $this->views[$region][] = $view;
139
        
140
        return $this;
141
    }
142
143
144
145
    /**
146
     * Check if a region has views to render.
147
     *
148
     * @param string $region which region to check
149
     *
150
     * @return $this
151
     */
152
    public function hasContent($region)
153
    {
154
        return isset($this->views[$region]);
155
    }
156
157
158
159
    /**
160
     * Set the app object to inject into view rendering phase.
161
     *
162
     * @param object $app with framework resources.
163
     *
164
     * @return $this
165
     */
166
    public function setApp($app)
167
    {
168
        $this->app = $app;
169
        return $this;
170
    }
171
172
173
174
    /**
175
     * Render all views for a specific region.
176
     *
177
     * @param string $region which region to use
178
     *
179
     * @return void
180
     */
181
    public function render($region = "main")
182
    {
183
        if (!isset($this->views[$region])) {
184
            return $this;
185
        }
186
187
        mergesort($this->views[$region], function ($viewA, $viewB) {
188
            $sortA = $viewA->sortOrder();
189
            $sortB = $viewB->sortOrder();
190
191
            if ($sortA == $sortB) {
192
                return 0;
193
            }
194
195
            return $sortA < $sortB ? -1 : 1;
196
        });
197
198
        foreach ($this->views[$region] as $view) {
199
            $view->render($this->app);
200
        }
201
    }
202
203
204
    /**
205
     * Render all views for a specific region and buffer the result.
206
     *
207
     * @param string $region which region to use.
208
     *
209
     * @return string with the buffered results.
210
     */
211
    public function renderBuffered($region = "main")
212
    {
213
        ob_start();
214
        $this->render($region);
215
        $res = ob_get_contents();
216
        ob_end_clean();
217
        return $res;
218
    }
219
}
220