BladeCompiler.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. <?php
  2. namespace Illuminate\View\Compilers;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Str;
  5. class BladeCompiler extends Compiler implements CompilerInterface
  6. {
  7. use Concerns\CompilesAuthorizations,
  8. Concerns\CompilesComments,
  9. Concerns\CompilesComponents,
  10. Concerns\CompilesConditionals,
  11. Concerns\CompilesEchos,
  12. Concerns\CompilesHelpers,
  13. Concerns\CompilesIncludes,
  14. Concerns\CompilesInjections,
  15. Concerns\CompilesJson,
  16. Concerns\CompilesLayouts,
  17. Concerns\CompilesLoops,
  18. Concerns\CompilesRawPhp,
  19. Concerns\CompilesStacks,
  20. Concerns\CompilesTranslations;
  21. /**
  22. * All of the registered extensions.
  23. *
  24. * @var array
  25. */
  26. protected $extensions = [];
  27. /**
  28. * All custom "directive" handlers.
  29. *
  30. * @var array
  31. */
  32. protected $customDirectives = [];
  33. /**
  34. * All custom "condition" handlers.
  35. *
  36. * @var array
  37. */
  38. protected $conditions = [];
  39. /**
  40. * The file currently being compiled.
  41. *
  42. * @var string
  43. */
  44. protected $path;
  45. /**
  46. * All of the available compiler functions.
  47. *
  48. * @var array
  49. */
  50. protected $compilers = [
  51. 'Comments',
  52. 'Extensions',
  53. 'Statements',
  54. 'Echos',
  55. ];
  56. /**
  57. * Array of opening and closing tags for raw echos.
  58. *
  59. * @var array
  60. */
  61. protected $rawTags = ['{!!', '!!}'];
  62. /**
  63. * Array of opening and closing tags for regular echos.
  64. *
  65. * @var array
  66. */
  67. protected $contentTags = ['{{', '}}'];
  68. /**
  69. * Array of opening and closing tags for escaped echos.
  70. *
  71. * @var array
  72. */
  73. protected $escapedTags = ['{{{', '}}}'];
  74. /**
  75. * The "regular" / legacy echo string format.
  76. *
  77. * @var string
  78. */
  79. protected $echoFormat = 'e(%s)';
  80. /**
  81. * Array of footer lines to be added to template.
  82. *
  83. * @var array
  84. */
  85. protected $footer = [];
  86. /**
  87. * Array to temporary store the raw blocks found in the template.
  88. *
  89. * @var array
  90. */
  91. protected $rawBlocks = [];
  92. /**
  93. * Compile the view at the given path.
  94. *
  95. * @param string $path
  96. * @return void
  97. */
  98. public function compile($path = null)
  99. {
  100. if ($path) {
  101. $this->setPath($path);
  102. }
  103. if (! is_null($this->cachePath)) {
  104. $contents = $this->compileString($this->files->get($this->getPath()));
  105. $this->files->put($this->getCompiledPath($this->getPath()), $contents);
  106. }
  107. }
  108. /**
  109. * Get the path currently being compiled.
  110. *
  111. * @return string
  112. */
  113. public function getPath()
  114. {
  115. return $this->path;
  116. }
  117. /**
  118. * Set the path currently being compiled.
  119. *
  120. * @param string $path
  121. * @return void
  122. */
  123. public function setPath($path)
  124. {
  125. $this->path = $path;
  126. }
  127. /**
  128. * Compile the given Blade template contents.
  129. *
  130. * @param string $value
  131. * @return string
  132. */
  133. public function compileString($value)
  134. {
  135. if (strpos($value, '@verbatim') !== false) {
  136. $value = $this->storeVerbatimBlocks($value);
  137. }
  138. $this->footer = [];
  139. if (strpos($value, '@php') !== false) {
  140. $value = $this->storePhpBlocks($value);
  141. }
  142. $result = '';
  143. // Here we will loop through all of the tokens returned by the Zend lexer and
  144. // parse each one into the corresponding valid PHP. We will then have this
  145. // template as the correctly rendered PHP that can be rendered natively.
  146. foreach (token_get_all($value) as $token) {
  147. $result .= is_array($token) ? $this->parseToken($token) : $token;
  148. }
  149. if (! empty($this->rawBlocks)) {
  150. $result = $this->restoreRawContent($result);
  151. }
  152. // If there are any footer lines that need to get added to a template we will
  153. // add them here at the end of the template. This gets used mainly for the
  154. // template inheritance via the extends keyword that should be appended.
  155. if (count($this->footer) > 0) {
  156. $result = $this->addFooters($result);
  157. }
  158. return $result;
  159. }
  160. /**
  161. * Store the verbatim blocks and replace them with a temporary placeholder.
  162. *
  163. * @param string $value
  164. * @return string
  165. */
  166. protected function storeVerbatimBlocks($value)
  167. {
  168. return preg_replace_callback('/(?<!@)@verbatim(.*?)@endverbatim/s', function ($matches) {
  169. return $this->storeRawBlock($matches[1]);
  170. }, $value);
  171. }
  172. /**
  173. * Store the PHP blocks and replace them with a temporary placeholder.
  174. *
  175. * @param string $value
  176. * @return string
  177. */
  178. protected function storePhpBlocks($value)
  179. {
  180. return preg_replace_callback('/(?<!@)@php(.*?)@endphp/s', function ($matches) {
  181. return $this->storeRawBlock("<?php{$matches[1]}?>");
  182. }, $value);
  183. }
  184. /**
  185. * Store a raw block and return a unique raw placeholder.
  186. *
  187. * @param string $value
  188. * @return string
  189. */
  190. protected function storeRawBlock($value)
  191. {
  192. return $this->getRawPlaceholder(
  193. array_push($this->rawBlocks, $value) - 1
  194. );
  195. }
  196. /**
  197. * Replace the raw placeholders with the original code stored in the raw blocks.
  198. *
  199. * @param string $result
  200. * @return string
  201. */
  202. protected function restoreRawContent($result)
  203. {
  204. $result = preg_replace_callback('/'.$this->getRawPlaceholder('(\d+)').'/', function ($matches) {
  205. return $this->rawBlocks[$matches[1]];
  206. }, $result);
  207. $this->rawBlocks = [];
  208. return $result;
  209. }
  210. /**
  211. * Get a placeholder to temporary mark the position of raw blocks.
  212. *
  213. * @param int|string $replace
  214. * @return string
  215. */
  216. protected function getRawPlaceholder($replace)
  217. {
  218. return str_replace('#', $replace, '@__raw_block_#__@');
  219. }
  220. /**
  221. * Add the stored footers onto the given content.
  222. *
  223. * @param string $result
  224. * @return string
  225. */
  226. protected function addFooters($result)
  227. {
  228. return ltrim($result, PHP_EOL)
  229. .PHP_EOL.implode(PHP_EOL, array_reverse($this->footer));
  230. }
  231. /**
  232. * Parse the tokens from the template.
  233. *
  234. * @param array $token
  235. * @return string
  236. */
  237. protected function parseToken($token)
  238. {
  239. list($id, $content) = $token;
  240. if ($id == T_INLINE_HTML) {
  241. foreach ($this->compilers as $type) {
  242. $content = $this->{"compile{$type}"}($content);
  243. }
  244. }
  245. return $content;
  246. }
  247. /**
  248. * Execute the user defined extensions.
  249. *
  250. * @param string $value
  251. * @return string
  252. */
  253. protected function compileExtensions($value)
  254. {
  255. foreach ($this->extensions as $compiler) {
  256. $value = call_user_func($compiler, $value, $this);
  257. }
  258. return $value;
  259. }
  260. /**
  261. * Compile Blade statements that start with "@".
  262. *
  263. * @param string $value
  264. * @return string
  265. */
  266. protected function compileStatements($value)
  267. {
  268. return preg_replace_callback(
  269. '/\B@(@?\w+(?:::\w+)?)([ \t]*)(\( ( (?>[^()]+) | (?3) )* \))?/x', function ($match) {
  270. return $this->compileStatement($match);
  271. }, $value
  272. );
  273. }
  274. /**
  275. * Compile a single Blade @ statement.
  276. *
  277. * @param array $match
  278. * @return string
  279. */
  280. protected function compileStatement($match)
  281. {
  282. if (Str::contains($match[1], '@')) {
  283. $match[0] = isset($match[3]) ? $match[1].$match[3] : $match[1];
  284. } elseif (isset($this->customDirectives[$match[1]])) {
  285. $match[0] = $this->callCustomDirective($match[1], Arr::get($match, 3));
  286. } elseif (method_exists($this, $method = 'compile'.ucfirst($match[1]))) {
  287. $match[0] = $this->$method(Arr::get($match, 3));
  288. }
  289. return isset($match[3]) ? $match[0] : $match[0].$match[2];
  290. }
  291. /**
  292. * Call the given directive with the given value.
  293. *
  294. * @param string $name
  295. * @param string|null $value
  296. * @return string
  297. */
  298. protected function callCustomDirective($name, $value)
  299. {
  300. if (Str::startsWith($value, '(') && Str::endsWith($value, ')')) {
  301. $value = Str::substr($value, 1, -1);
  302. }
  303. return call_user_func($this->customDirectives[$name], trim($value));
  304. }
  305. /**
  306. * Strip the parentheses from the given expression.
  307. *
  308. * @param string $expression
  309. * @return string
  310. */
  311. public function stripParentheses($expression)
  312. {
  313. if (Str::startsWith($expression, '(')) {
  314. $expression = substr($expression, 1, -1);
  315. }
  316. return $expression;
  317. }
  318. /**
  319. * Register a custom Blade compiler.
  320. *
  321. * @param callable $compiler
  322. * @return void
  323. */
  324. public function extend(callable $compiler)
  325. {
  326. $this->extensions[] = $compiler;
  327. }
  328. /**
  329. * Get the extensions used by the compiler.
  330. *
  331. * @return array
  332. */
  333. public function getExtensions()
  334. {
  335. return $this->extensions;
  336. }
  337. /**
  338. * Register an "if" statement directive.
  339. *
  340. * @param string $name
  341. * @param callable $callback
  342. * @return void
  343. */
  344. public function if($name, callable $callback)
  345. {
  346. $this->conditions[$name] = $callback;
  347. $this->directive($name, function ($expression) use ($name) {
  348. return $expression !== ''
  349. ? "<?php if (\Illuminate\Support\Facades\Blade::check('{$name}', {$expression})): ?>"
  350. : "<?php if (\Illuminate\Support\Facades\Blade::check('{$name}')): ?>";
  351. });
  352. $this->directive('else'.$name, function ($expression) use ($name) {
  353. return $expression !== ''
  354. ? "<?php elseif (\Illuminate\Support\Facades\Blade::check('{$name}', {$expression})): ?>"
  355. : "<?php elseif (\Illuminate\Support\Facades\Blade::check('{$name}')): ?>";
  356. });
  357. $this->directive('end'.$name, function () {
  358. return '<?php endif; ?>';
  359. });
  360. }
  361. /**
  362. * Check the result of a condition.
  363. *
  364. * @param string $name
  365. * @param array $parameters
  366. * @return bool
  367. */
  368. public function check($name, ...$parameters)
  369. {
  370. return call_user_func($this->conditions[$name], ...$parameters);
  371. }
  372. /**
  373. * Register a component alias directive.
  374. *
  375. * @param string $path
  376. * @param string $alias
  377. * @return void
  378. */
  379. public function component($path, $alias = null)
  380. {
  381. $alias = $alias ?: array_last(explode('.', $path));
  382. $this->directive($alias, function ($expression) use ($path) {
  383. return $expression
  384. ? "<?php \$__env->startComponent('{$path}', {$expression}); ?>"
  385. : "<?php \$__env->startComponent('{$path}'); ?>";
  386. });
  387. $this->directive('end'.$alias, function ($expression) {
  388. return '<?php echo $__env->renderComponent(); ?>';
  389. });
  390. }
  391. /**
  392. * Register an include alias directive.
  393. *
  394. * @param string $path
  395. * @param string $alias
  396. * @return void
  397. */
  398. public function include($path, $alias = null)
  399. {
  400. $alias = $alias ?: array_last(explode('.', $path));
  401. $this->directive($alias, function ($expression) use ($path) {
  402. $expression = $this->stripParentheses($expression) ?: '[]';
  403. return "<?php echo \$__env->make('{$path}', {$expression}, array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>";
  404. });
  405. }
  406. /**
  407. * Register a handler for custom directives.
  408. *
  409. * @param string $name
  410. * @param callable $handler
  411. * @return void
  412. */
  413. public function directive($name, callable $handler)
  414. {
  415. $this->customDirectives[$name] = $handler;
  416. }
  417. /**
  418. * Get the list of custom directives.
  419. *
  420. * @return array
  421. */
  422. public function getCustomDirectives()
  423. {
  424. return $this->customDirectives;
  425. }
  426. /**
  427. * Set the echo format to be used by the compiler.
  428. *
  429. * @param string $format
  430. * @return void
  431. */
  432. public function setEchoFormat($format)
  433. {
  434. $this->echoFormat = $format;
  435. }
  436. /**
  437. * Set the "echo" format to double encode entities.
  438. *
  439. * @return void
  440. */
  441. public function withDoubleEncoding()
  442. {
  443. $this->setEchoFormat('e(%s, true)');
  444. }
  445. /**
  446. * Set the "echo" format to not double encode entities.
  447. *
  448. * @return void
  449. */
  450. public function withoutDoubleEncoding()
  451. {
  452. $this->setEchoFormat('e(%s, false)');
  453. }
  454. }