Completed
Push — master ( 579af5...b29473 )
by Oleg
07:53
created

PhpView::render()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 10
rs 9.4285
cc 3
eloc 5
nc 2
nop 0
1
<?php /** MicroPhpView */
2
3
namespace Micro\Mvc\Views;
4
5
use Micro\Base\Exception;
6
use Micro\Web\Language;
7
8
/**
9
 * Class PhpView
10
 *
11
 * @author Oleg Lunegov <[email protected]>
12
 * @link https://github.com/lugnsk/micro
13
 * @copyright Copyright &copy; 2013 Oleg Lunegov
14
 * @license /LICENSE
15
 * @package Micro
16
 * @subpackage Mvc/Views
17
 * @version 1.0
18
 * @since 1.0
19
 */
20
class PhpView extends View
21
{
22
    /** @var string Layout to render */
23
    public $layout;
24
    /** @var string $view View name */
25
    public $view;
26
    /** @var string $path Path to view */
27
    public $path;
28
    /** @var string $data Return data */
29
    public $data = '';
30
31
    /**
32
     * Render partial
33
     *
34
     * @access public
35
     *
36
     * @param string $view view name
37
     *
38
     * @return string
39
     * @throws Exception
40
     */
41
    public function renderPartial($view)
42
    {
43
        $lay = $this->layout;
44
        $wi  = $this->view;
45
46
        $this->layout = null;
47
        $this->view   = $view;
48
        $output       = $this->render();
49
        $this->layout = $lay;
50
        $this->view   = $wi;
51
52
        return $output;
53
    }
54
55
    /**
56
     * Render insert data into view
57
     *
58
     * @access protected
59
     *
60
     * @return string
61
     * @throws Exception
62
     */
63
    public function render()
64
    {
65
        if (!$this->view) {
66
            return false;
67
        }
68
69
        return $this->renderRawData(
70
            ($this->data) ?: $this->renderFile($this->getViewFile($this->view), $this->params)
71
        );
72
    }
73
74
    /**
75
     * Render raw data in layout
76
     *
77
     * @access public
78
     * @global       Micro
79
     * @global       Container
80
     *
81
     * @param string $data arguments array
82
     *
83
     * @return string
84
     * @throws Exception
85
     */
86
    public function renderRawData($data = '')
87
    {
88
        $layoutPath = null;
89
        if ($this->layout) {
90
            $layoutPath = $this->getLayoutFile($this->container->kernel->getAppDir(), $this->module);
0 ignored issues
show
Bug introduced by
Accessing kernel on the interface Micro\Base\IContainer suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
Documentation introduced by
$this->module is of type object<Micro\Mvc\Module>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
91
        }
92
93
        if ($layoutPath) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $layoutPath of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
94
            $data = $this->insertStyleScripts($this->renderFile($layoutPath, ['content' => $data]));
95
        }
96
97
        return $data;
98
    }
99
100
    /**
101
     * Get layout path
102
     *
103
     * @access protected
104
     *
105
     * @param string $appDir path to base dir
106
     * @param string $module module name
107
     *
108
     * @return string
109
     * @throws Exception
110
     */
111
    protected function getLayoutFile($appDir, $module)
112
    {
113
        if ($module) {
114
            $module = str_replace('\\', '/', substr($module, 4));
115
            $module = substr($module, 0, strrpos($module, '/'));
116
        }
117
118
        $layout = $appDir . '/' . (($module) ? $module . '/' : $module);
119
        $afterPath = 'views/layouts/' . ucfirst($this->layout) . '.php';
120
121
        if (!file_exists($layout . $afterPath)) {
122
            if (file_exists($appDir . '/' . $afterPath)) {
123
                return $appDir . '/' . $afterPath;
124
            }
125
            throw new Exception('Layout ' . ucfirst($this->layout) . ' not found.');
126
        }
127
128
        return $layout . $afterPath;
129
    }
130
131
    /**
132
     * Render file by path
133
     *
134
     * @access protected
135
     *
136
     * @param string $fileName file name
137
     * @param array $data arguments array
138
     *
139
     * @return string
140
     * @throws Exception widget not declared
141
     */
142
    protected function renderFile($fileName, array $data = [])
0 ignored issues
show
Coding Style introduced by
renderFile uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
143
    {
144
        /** @noinspection OnlyWritesOnParameterInspection */
145
        /** @noinspection PhpUnusedLocalVariableInspection */
146
        $lang = new Language($this->container, $fileName);
147
        extract($data, EXTR_PREFIX_SAME || EXTR_REFS, 'data');
148
        ob_start();
149
150
        /** @noinspection PhpIncludeInspection */
151
        include str_replace('\\', '/', $fileName);
152
153 View Code Duplication
        if (!empty($GLOBALS['widgetStack'])) {
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...
154
            throw new Exception(count($GLOBALS['widgetStack']) . ' widgets not endings.');
155
        }
156
157
        return ob_get_clean();
158
    }
159
160
    /**
161
     * Get view file
162
     *
163
     * @access private
164
     *
165
     * @param string $view view file name
166
     *
167
     * @return string
168
     * @throws Exception
169
     */
170
    private function getViewFile($view)
171
    {
172
        $calledClass = $this->path;
173
174
        // Calculate path to view
175
        if (substr($calledClass, 0, strpos($calledClass, '\\')) === 'App') {
176
            $path = $this->container->kernel->getAppDir();
0 ignored issues
show
Bug introduced by
Accessing kernel on the interface Micro\Base\IContainer suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
177
        } else {
178
            $path = $this->container->kernel->getMicroDir();
0 ignored issues
show
Bug introduced by
Accessing kernel on the interface Micro\Base\IContainer suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
179
        }
180
181
        $cl = strtolower(dirname(str_replace('\\', '/', $calledClass)));
182
        $cl = substr($cl, strpos($cl, '/'));
183
184
        if ($this->asWidget) {
185
            $path .= $cl . '/views/' . $view . '.php';
186
        } else {
187
            $className = str_replace('controller', '',
188
                strtolower(basename(str_replace('\\', '/', '/' . $this->path))));
189
            $path .= dirname($cl) . '/views/' . $className . '/' . $view . '.php';
190
        }
191
192
        $path = str_replace('//', '/', $path);
193
194
        if (!file_exists($path)) {
195
            throw new Exception('View path `' . $path . '` not exists.');
196
        }
197
198
        return $path;
199
    }
200
}
201