summaryrefslogtreecommitdiff
path: root/src/View.php
blob: 761ef626bb7f8e1512055ad3e0dea2e912f58e1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php

namespace App;

use Twig\Environment;
use Twig\Extension\DebugExtension;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFilter;

class View
{
  public static Environment $twig;

  public static function init(): void
  {
    $loader = new FilesystemLoader(
      dirname(__DIR__) . '/views/' .
      (isset($_ENV['GEMINI']) ? 'gemini' : 'http')
    );
    self::$twig = new Environment($loader, [
      'debug' => $_ENV['APP_ENV'] === 'development',
    ]);

    self::$twig->addExtension(new DebugExtension());
    // self::$twig->addExtension(new IntlExtension());

    self::$twig->addFilter(new TwigFilter('buildTime', function ($buildTime) {
      if ($buildTime > 3600*24) {
        return @sprintf('%02d:%02d:%02d:%02d', $buildTime / (3600*24), $buildTime / 3600, ($buildTime / 60) % 60, $buildTime % 60);
      }

      return @sprintf('%02d:%02d:%02d', $buildTime / 3600, ($buildTime / 60) % 60, $buildTime % 60);
    }));
  }

  public static function addGlobal(string $name, mixed $value): void
  {
    self::$twig->addGlobal($name, $value);
  }

  /**
   * @param string $name
   * @param array $context
   */
  public static function render(string $name, array $context = []): string
  {
    if (isset($_ENV['GEMINI'])) {
      $string = self::$twig->render($name, $context);
      $lines = explode(PHP_EOL, $string);
      $output = '';

      foreach ($lines as $line) {
        $output .= ltrim($line, ' \t') . "\r\n";
      }

      return $output;
    } else {
      return self::$twig->render($name, $context);
    }
  }
}