1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link https://github.com/vuongxuongminh/yii2-mobile-first |
4
|
|
|
* @copyright Copyright (c) 2019 Vuong Xuong Minh |
5
|
|
|
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php) |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace vxm\mobileFirst; |
9
|
|
|
|
10
|
|
|
use yii\base\ViewRenderer as BaseViewRenderer; |
11
|
|
|
use yii\di\Instance; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* The renderer support rendering view in sub dir of it. |
15
|
|
|
* |
16
|
|
|
* @author Vuong Minh <[email protected]> |
17
|
|
|
* @since 1.0.0 |
18
|
|
|
*/ |
19
|
|
|
class ViewRenderer extends BaseViewRenderer |
20
|
|
|
{ |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Origin renderer using to render file if not set [[View::renderPhpFile]] will be use. |
24
|
|
|
* |
25
|
|
|
* @var null|ViewRenderer |
26
|
|
|
*/ |
27
|
|
|
public $renderer; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var string the device dir |
31
|
|
|
* @see [[getFile()]] |
32
|
|
|
*/ |
33
|
|
|
public $dir; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @inheritDoc |
37
|
|
|
*/ |
38
|
6 |
|
public function init() |
39
|
|
|
{ |
40
|
6 |
|
if ($this->renderer) { |
41
|
|
|
|
42
|
6 |
|
$this->renderer = Instance::ensure($this->renderer, 'yii\base\ViewRenderer'); |
43
|
|
|
} |
44
|
|
|
|
45
|
6 |
|
parent::init(); |
46
|
6 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @inheritDoc |
50
|
|
|
* @throws \Throwable |
51
|
|
|
*/ |
52
|
6 |
|
public function render($view, $file, $params) |
53
|
|
|
{ |
54
|
6 |
|
$file = $this->getFile($file); |
55
|
|
|
|
56
|
6 |
|
if ($this->renderer) { |
57
|
|
|
|
58
|
6 |
|
$output = $this->renderer->render($view, $file, $params); |
59
|
|
|
} else { |
60
|
|
|
|
61
|
|
|
$output = $view->renderPhpFile($file, $params); |
62
|
|
|
} |
63
|
|
|
|
64
|
6 |
|
$ext = pathinfo($file, PATHINFO_EXTENSION); |
65
|
|
|
|
66
|
6 |
|
if ($view->renderers[$ext] === $this) { |
67
|
6 |
|
$view->renderers[$ext] = $this->renderer; |
68
|
|
|
} |
69
|
|
|
|
70
|
6 |
|
return $output; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Returns the file version of a specified [[$dir]]. |
75
|
|
|
* |
76
|
|
|
* @param string $baseFile |
77
|
|
|
* @return string |
78
|
|
|
*/ |
79
|
6 |
|
protected function getFile(string $baseFile): string |
80
|
|
|
{ |
81
|
6 |
|
if ($dir = $this->dir) { |
82
|
|
|
|
83
|
4 |
|
$basePath = pathinfo($baseFile, PATHINFO_DIRNAME); |
84
|
4 |
|
$fileName = pathinfo($baseFile, PATHINFO_BASENAME); |
85
|
4 |
|
$desiredFile = $basePath . '/' . $dir . '/' . $fileName; |
86
|
|
|
|
87
|
4 |
|
return is_file($desiredFile) ? $desiredFile : $baseFile; |
88
|
|
|
} else { |
89
|
|
|
|
90
|
2 |
|
return $baseFile; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|