move formatting from JS to PHP
[mdref/mdref] / mdref / Generator / Template.php
1 <?php
2
3 namespace mdref\Generator;
4
5 use http\Exception\RuntimeException;
6
7 class Template {
8 public function __construct(
9 private string $file,
10 private int $offset
11 ) {}
12
13 public function source() {
14 return file_get_contents($this->file, false, null, $this->offset);
15 }
16
17 private function cache(string $cache_file) : string {
18 $cache_path = dirname($cache_file);
19 if (!is_dir($cache_path) && !mkdir($cache_path, 0700, true)) {
20 throw new RuntimeException(error_get_last()["message"]);
21 }
22 if (!file_put_contents($cache_file, '<?php namespace mdref\\Generator; ?>' . $this->source())) {
23 throw new RuntimeException(error_get_last()["message"]);
24 }
25 return $cache_file;
26 }
27
28 public function __toString() : string {
29 $cache_file = sys_get_temp_dir() . "/mdref/generate." . basename($this->file) . ".md.tmp";
30 $cache_stat = @stat($cache_file);
31 if ($cache_stat && $cache_stat["mtime"] >= filemtime($this->file)) {
32 return $cache_file;
33 }
34
35 return $this->cache($cache_file);
36 }
37 }