CatalogueCompiler   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 3
Metric Value
wmc 11
eloc 36
c 4
b 0
f 3
dl 0
loc 66
rs 10
ccs 32
cts 32
cp 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getCatalogueFilename() 0 2 1
A isCatalogueExpired() 0 16 5
A __construct() 0 7 2
A compile() 0 17 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Nexendrie\Translation;
5
6
use Nette\PhpGenerator\Helpers;
7
use Nette\Utils\FileSystem;
8
9
/**
10
 * CatalogueCompiler
11
 * Compiles messages catalogues from resources found by loader
12
 *
13
 * @author Jakub Konečný
14
 * @method void onCompile(CatalogueCompiler $compiler, string $language)
15
 */
16 1
final class CatalogueCompiler {
17 1
  use \Nette\SmartObject;
18
  
19
  /** @var ILoader */
20
  protected $loader;
21
  /** @var string[] */
22
  protected $languages = [];
23
  /** @var string */
24
  protected $folder = "";
25
  /** @var callable[] */
26
  public $onCompile = [];
27
  
28
  /**
29
   * @param string[] $languages
30
   */
31
  public function __construct(ILoader $loader, string $folder, array $languages = []) {
32 1
    $this->loader = $loader;
33 1
    if(count($languages) === 0) {
34 1
      $languages = $loader->getAvailableLanguages();
35
    }
36 1
    $this->languages = $languages;
37 1
    $this->folder = $folder;
38 1
  }
39
  
40
  protected function getCatalogueFilename(string $language): string {
41 1
    return $this->folder . "/catalogue.$language.php";
42
  }
43
  
44
  protected function isCatalogueExpired(string $language): bool {
45 1
    $catalogueFilename = $this->getCatalogueFilename($language);
46 1
    if(!is_file($catalogueFilename)) {
47 1
      return true;
48
    }
49 1
    $catalogueInfo = new \SplFileInfo($catalogueFilename);
50 1
    $lastGenerated = $catalogueInfo->getCTime();
51 1
    foreach($this->loader->getResources() as $domain) {
52 1
      foreach($domain as $filename) {
53 1
        $fileinfo = new \SplFileInfo($filename);
54 1
        if($fileinfo->getMTime() > $lastGenerated) {
55 1
          return true;
56
        }
57
      }
58
    }
59 1
    return false;
60
  }
61
  
62
  /**
63
   * Compile catalogues
64
   */
65
  public function compile(): void {
66 1
    $lang = $this->loader->getLang();
67 1
    foreach($this->languages as $language) {
68 1
      $this->loader->setLang($language);
69 1
      $texts = $this->loader->getTexts();
70 1
      if(!$this->isCatalogueExpired($language)) {
71 1
        continue;
72
      }
73 1
      $texts["__resources"] = $this->loader->getResources();
74
      $content = "<?php
75 1
return " . Helpers::dump($texts) . ";
76
?>";
77 1
      $filename = $this->getCatalogueFilename($language);
78 1
      FileSystem::write($filename, $content);
79 1
      $this->onCompile($this, $language);
80
    }
81 1
    $this->loader->setLang($lang);
82 1
  }
83
}
84
?>