Script.php
2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/**
* Created by PhpStorm.
* User: Zip
* Date: 14/12/16
* Time: 下午12:59
*/
namespace Hood\Helper\View;
class Script extends ViewAbstract
{
protected $_attributes = array(
'charset', 'defer', 'language', 'src'
);
protected $_attrList = array(
'charset="UTF-8"',
'type="text/javascript"',
);
protected $_fieldsFile = array();
public function offsetSetFile($index, $src, $conditional = '')
{
$this->_item[$index] = $src;
if (!empty($conditional)) {
$this->_target_conditional[$index] = $conditional;
}
return $this;
}
/**
* 保留输出文件
* @param array $fieldsIDS
* @return $this
*/
public function fieldsFile(array $fieldsIDS)
{
$this->_fieldsFile = $fieldsIDS;
return $this;
}
public function appendFile($src)
{
$this->_item[] = $src;
}
public function setAttr(array $attr)
{
foreach ($attr as $_attr => $val) {
if (isset($this->_attrList[$_attr]) && !empty($val) && is_string($val)) {
$this->_attrList[] = sprintf(' %s="%s"', $_attr, htmlspecialchars($val, ENT_COMPAT, $this->enc));
}
}
return $this;
}
public function conditional($conditional = 'lt IE 9')
{
assert(is_string($conditional));
$this->conditional = $conditional;
return $this;
}
public function __toString()
{
$html = '';
$_attrString = implode(' ', $this->_attrList);
foreach ($this->_item as $key => $val) {
if (empty($val)) {
continue;
}
$_script = '<script src="' . $val . '" ' . $_attrString . '></script>' . PHP_EOL;
if (isset($this->_target_conditional[$key])) {
$html .= '<!--[if ' . $this->_target_conditional[$key] . ']> ' . PHP_EOL . $_script . '<![endif]-->' . PHP_EOL;
} else {
$html .= $_script;
}
}
if (!empty($this->conditional) && empty($this->_target_conditional)) {
$html = '<!--[if ' . $this->conditional . ']> ' . PHP_EOL . $html . '<![endif]-->' . PHP_EOL;
}
return $html;
}
}