1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Latte;
9:
10:
11: 12: 13: 14: 15:
16: class Helpers
17: {
18:
19: public static $emptyElements = array(
20: 'img'=>1,'hr'=>1,'br'=>1,'input'=>1,'meta'=>1,'area'=>1,'embed'=>1,'keygen'=>1,'source'=>1,'base'=>1,
21: 'col'=>1,'link'=>1,'param'=>1,'basefont'=>1,'frame'=>1,'isindex'=>1,'wbr'=>1,'command'=>1,'track'=>1
22: );
23:
24:
25: 26: 27: 28:
29: public static function checkCallback($callable)
30: {
31: if (!is_callable($callable, FALSE, $text)) {
32: throw new \InvalidArgumentException("Callback '$text' is not callable.");
33: }
34: return $callable;
35: }
36:
37:
38: 39: 40: 41: 42:
43: public static function optimizePhp($source, $lineLength = 80)
44: {
45: $res = $php = '';
46: $lastChar = ';';
47: $tokens = new \ArrayIterator(token_get_all($source));
48: foreach ($tokens as $n => $token) {
49: if (is_array($token)) {
50: if ($token[0] === T_INLINE_HTML) {
51: $lastChar = '';
52: $res .= $token[1];
53:
54: } elseif ($token[0] === T_CLOSE_TAG) {
55: $next = isset($tokens[$n + 1]) ? $tokens[$n + 1] : NULL;
56: if (substr($res, -1) !== '<' && preg_match('#^<\?php\s*\z#', $php)) {
57: $php = '';
58:
59: } elseif (is_array($next) && $next[0] === T_OPEN_TAG && (!isset($tokens[$n + 2][1]) || $tokens[$n + 2][1] !== 'xml')) {
60: if (!strspn($lastChar, ';{}:/')) {
61: $php .= $lastChar = ';';
62: }
63: if (substr($next[1], -1) === "\n") {
64: $php .= "\n";
65: }
66: $tokens->next();
67:
68: } elseif ($next) {
69: $res .= preg_replace('#;?(\s)*\z#', '$1', $php) . $token[1];
70: if (strlen($res) - strrpos($res, "\n") > $lineLength
71: && (!is_array($next) || strpos($next[1], "\n") === FALSE)
72: ) {
73: $res .= "\n";
74: }
75: $php = '';
76:
77: } else {
78: if (!strspn($lastChar, '};')) {
79: $php .= ';';
80: }
81: }
82:
83: } elseif ($token[0] === T_ELSE || $token[0] === T_ELSEIF) {
84: if ($tokens[$n + 1] === ':' && $lastChar === '}') {
85: $php .= ';';
86: }
87: $lastChar = '';
88: $php .= $token[1];
89:
90: } elseif ($token[0] === T_OPEN_TAG && $token[1] === '<?' && isset($tokens[$n+1][1]) && $tokens[$n+1][1] === 'xml') {
91: $lastChar = '';
92: $res .= '<<?php ?>?';
93: for ($tokens->next(); $tokens->valid(); $tokens->next()) {
94: $token = $tokens->current();
95: $res .= is_array($token) ? $token[1] : $token;
96: if ($token[0] === T_CLOSE_TAG) {
97: break;
98: }
99: }
100:
101: } else {
102: if (!in_array($token[0], array(T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_OPEN_TAG), TRUE)) {
103: $lastChar = '';
104: }
105: $php .= $token[1];
106: }
107: } else {
108: $php .= $lastChar = $token;
109: }
110: }
111: return $res . $php;
112: }
113:
114: }
115: