NanoFramework 1.4.0
A tiny PHP Framework
View.php
Go to the documentation of this file.
1<?php
2
4
10class View
11{
21 public function parseFile(string $source, array $variables = [], array $rawVariables = []): string
22 {
23 return rtrim($this->parse(file_get_contents($source), $variables, $rawVariables), PHP_EOL);
24 }
25
37 public function parse(string $content, array $variables = [], array $rawVariables = []): string
38 {
39 $content = preg_replace_callback('#\{\s*if\s*(\w+)\s*\}(.*)(?:\{\s*else\s*\}(.*))?\{\s*endif\s*\}#Ums', function ($matches) use ($variables, $rawVariables) {
40 $condition = $variables[$matches[1]] ?? $rawVariables[$matches[1]] ?? false;
41 if ($condition) {
42 return $this->parse($matches[2], $variables, $rawVariables);
43 }
44 if (count($matches) > 3) {
45 return $this->parse($matches[3], $variables, $rawVariables);
46 }
47
48 return '';
49 }, $content);
50 foreach ($variables as $key => $value) {
51 if (is_array($value)) {
52 $content = preg_replace_callback('#\{\s*' . $key . '\s*\}((?:.|[\n\r])*)\{/\s*' . $key . '\s*\}#Um', function (array $matches) use ($value, $variables, $rawVariables) {
53 $innerContent = '';
54 foreach ($value as $innerElement => $attributes) {
55 $innerContent .= $this->parse($matches[1], array_merge($variables, $attributes), $rawVariables);
56 }
57
58 return $innerContent;
59 }, $content);
60 } else {
61 $content = preg_replace('#\{' . $key . '\}#', htmlspecialchars($value), $content);
62 }
63 }
64
65 foreach ($rawVariables as $key => $value) {
66 if (is_array($value)) {
67 $content = preg_replace_callback('#\{\s*' . $key . '\s*\}((?:.|[\n\r])*)\{/\s*' . $key . '\s*\}#Um', function (array $matches) use ($value, $variables, $rawVariables) {
68 $innerContent = '';
69 foreach ($value as $innerElement => $attributes) {
70 $innerContent .= $this->parse($matches[1], $variables, array_merge($rawVariables, $attributes));
71 }
72
73 return $innerContent;
74 }, $content);
75 } else {
76 $content = preg_replace('#\{' . $key . '\}#', $value, $content);
77 }
78 }
79
80 return $content;
81 }
82}
Parses files to insert data.
Definition: View.php:11
parseFile(string $source, array $variables=[], array $rawVariables=[])
Definition: View.php:21
parse(string $content, array $variables=[], array $rawVariables=[])
Definition: View.php:37