Passed
Push — develop ( 0abda6...022345 )
by Michael
04:34
created

src/View.php (1 issue)

Check for loose comparison of strings.

Best Practice Bug Major

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 * This file is part of the miBadger package.
5
 *
6
 * @author Michael Webbers <[email protected]>
7
 * @license http://opensource.org/licenses/Apache-2.0 Apache v2 License
8
 */
9
10
namespace miBadger\Mvc;
11
12
use miBadger\Singleton\SingletonTrait;
13
14
/**
15
 * The view class of the MVC pattern.
16
 *
17
 * @see http://en.wikipedia.org/wiki/Model-view-controller
18
 * @since 1.0.0
19
 */
20
class View
21
{
22
	use SingletonTrait;
23
24
	const DIRECTORY_SEPARATOR = \DIRECTORY_SEPARATOR;
25
26
	/** @var string|null the base path. */
27
	private $basePath;
28
29
	/**
30
	 * Construct a object.
31
	 */
32 4
	protected function __construct()
33
	{
34 4
		$this->basePath = null;
35 4
	}
36
37
	/**
38
	 * Returns the base path.
39
	 *
40
	 * @return string the base path.
41
	 */
42 2
	public static function getBasePath()
43
	{
44 2
		return static::getInstance()->basePath;
45
	}
46
47
	/**
48
	 * Set the base path.
49
	 *
50
	 * @param string|null $basePath = null
51
	 */
52 2
	public static function setBasePath($basePath = null)
53
	{
54 2
		static::getInstance()->basePath = $basePath;
55 2
	}
56
57
	/**
58
	 * Returns the view at the given path with the given data.
59
	 *
60
	 * @param string $path
61
	 * @param string[] $data = []
62
	 * @return string a string representation of the view.
63
	 */
64 2
	public static function get($path, $data = [])
65
	{
66 2
		ob_start();
67
68 2
		extract($data);
69
70
		try {
71 2
			$basePath = static::getInstance()->basePath;
72
73 2
			if ($basePath) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $basePath 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...
74 1
				if (mb_substr($path, 0, 1) === static::DIRECTORY_SEPARATOR) {
75 1
					$path = mb_substr($path, 1);
76
				}
77
78 1
				if (mb_substr($basePath, -1) === static::DIRECTORY_SEPARATOR) {
79 1
					$basePath = mb_substr($basePath, 0, -1);
80
				}
81
82 1
				$path = $basePath . static::DIRECTORY_SEPARATOR . $path;
83
			}
84
85 2
			include $path;
86 1
		} catch (\Exception $e) {
87 1
			ob_get_clean();
88 1
			throw $e;
89
		}
90
91 1
		return ob_get_clean();
92
	}
93
}
94