Skip to content

Commit 596a403

Browse files
authored
Create Template.php
1 parent f97754b commit 596a403

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Template.php

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
namespace core;
3+
4+
// Template is used for simple page rendering with PHP
5+
// in an opiniated way (maximizing productivity for the developer in a multi-language environment)
6+
class Template {
7+
public string $base = __DIR__;
8+
9+
private array $cache_langs = []; // cached language files
10+
private array $missing_text = []; // sentences that currently lack a translation [lang]=[sentence1,sentence2...]
11+
12+
// langfile loads the given file for a language (caching it for fast performance)
13+
public function langfile(string $lang, string $file): ?array {
14+
if ($lang === "en") user_error("already english");
15+
16+
$lookup = $this->cache_langs[$lang][$file] ?? null;
17+
if ($lookup === null) {
18+
$fname = $this->base . "/lang.d/$lang/static/$file.json";
19+
if (! file_exists($fname)) {
20+
echo sprintf("WARN: Lang(%s) missing langfile\n", $fname);
21+
} else {
22+
$lookup = json_decode(file_get_contents($fname), true);
23+
if (! is_array($lookup)) user_error("Failed decoding $fname");
24+
$cache_langs[$lang][$file] = $lookup; // cache if user later on
25+
}
26+
}
27+
return $lookup;
28+
}
29+
30+
// translate-func avail in templates
31+
public function translate(string $lang, string $file): callable {
32+
return function(string $english, array $args = []) use($lang, $file): string {
33+
if ($lang === "en") return $english;
34+
if (isset($args["file"])) {
35+
// Override file from template with underscore version
36+
// (i.e. used in header/footer to have one file for all pages)
37+
$file = sprintf("_%s.php", $args["file"]);
38+
}
39+
$lookup = $this->langfile($lang, $file);
40+
41+
if (! isset($lookup[ $english ])) {
42+
$this->missing_text[ $lang ][ $file ][ $english ] = $english; // Hint builder we don't have this and want it
43+
//fwrite(STDERR, sprintf("WARN: Lang(%s/%s) missing text=%s\n", $lang, $file, $english) );
44+
return $english;
45+
}
46+
return $lookup[ $english ];
47+
};
48+
}
49+
50+
// strip removes whitespaces to solve elements not pushed on eachother
51+
// i.e. products page the term selector
52+
public static function strip(string $htm): string {
53+
$htm = str_replace("\n", "", $htm);
54+
$htm = str_replace("\r", "", $htm);
55+
$htm = str_replace("\t", "", $htm);
56+
$htm = str_replace(" ", "", $htm);
57+
return $htm;
58+
}
59+
60+
public function missing(): array {
61+
return $this->missing_text;
62+
}
63+
}

0 commit comments

Comments
 (0)