Completed
Push — master ( 613a97...7ff9ca )
by Jakub
01:55
created

Generator::getMeta()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 4
nop 2
dl 0
loc 13
ccs 9
cts 9
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Nexendrie\SiteGenerator;
5
6
use cebe\markdown\GithubMarkdown,
7
    Nette\Utils\Finder,
8
    Nette\Neon\Neon,
9
    Nette\Utils\FileSystem,
10
    Symfony\Component\OptionsResolver\OptionsResolver,
11
    Nette\Utils\Validators;
12
13
/**
14
 * Generator
15
 *
16
 * @author Jakub Konečný
17
 * @property string $source
18
 * @property string $output
19
 * @method void onBeforeGenerate()
20
 * @method void onCreatePage(string $html, Generator $generator, string $filename)
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 82 characters
Loading history...
21
 * @method void onAfterGenerate()
22
 */
23 1
class Generator {
24 1
  use \Nette\SmartObject;
25
  
26
  /** @var string */
27
  protected $templateFile;
28
  /** @var string */
29
  protected $source;
30
  /** @var string */
31
  protected $output;
32
  /** @var string[] */
33
  protected $assets = [];
34
  /** @var callable[] */
35
  protected $metaNormalizers = [];
36
  /** @var callable[] */
37
  public $onBeforeGenerate = [];
38
  /** @var callable[] */
39
  public $onCreatePage = [];
40
  /** @var callable[] */
41
  public $onAfterGenerate = [];
42
  
43
  public function __construct(string $source, string $output) {
44 1
    $this->setSource($source);
45 1
    FileSystem::createDir($output);
46 1
    $this->setOutput($output);
47 1
    $this->templateFile = __DIR__ . "/template.html";
48 1
    $this->onBeforeGenerate[] = [$this, "clearOutputFolder"];
49 1
    $this->onCreatePage[] = [$this, "processImages"];
50 1
    $this->onAfterGenerate[] = [$this, "copyAssets"];
51 1
    $this->addMetaNormalizer([$this, "normalizeTitle"]);
52 1
    $this->addMetaNormalizer([$this, "normalizeStyles"]);
53 1
    $this->addMetaNormalizer([$this, "normalizeScripts"]);
54 1
  }
55
  
56
  public function addMetaNormalizer(callable $callback): void {
57 1
    $this->metaNormalizers[] = $callback;
58 1
  }
59
  
60
  public function getSource(): string {
61 1
    return $this->source;
62
  }
63
  
64
  public function setSource(string $source) {
65 1
    if(is_dir($source)) {
66 1
      $this->source = realpath($source);
67
    }
68 1
  }
69
  
70
  public function getOutput(): string {
71 1
    return $this->output;
72
  }
73
  
74
  public function setOutput(string $output) {
75 1
    $this->output = realpath($output);
76 1
  }
77
  
78
  protected function createMetaResolver(): OptionsResolver {
79 1
    $resolver = new OptionsResolver();
80 1
    $resolver->setDefaults([
81 1
      "title" => "",
82
      "styles" => [],
83
      "scripts" => [],
84
    ]);
85 1
    $isArrayOfStrings = function(array $value) {
86 1
      return Validators::everyIs($value, "string");
87
    };
88 1
    $resolver->setAllowedTypes("title", "string");
89 1
    $resolver->setAllowedTypes("styles", "array");
90 1
    $resolver->setAllowedValues("styles", $isArrayOfStrings);
91 1
    $resolver->setAllowedTypes("scripts", "array");
92 1
    $resolver->setAllowedValues("scripts", $isArrayOfStrings);
93 1
    return $resolver;
94
  }
95
  
96
  protected function getMeta(string $filename, string &$html): array {
97 1
    $resolver = $this->createMetaResolver();
98 1
    $metaFilename = str_replace(".md", ".neon", $filename);
99 1
    $meta = [];
100 1
    if(file_exists($metaFilename)) {
101 1
      $meta = Neon::decode(file_get_contents($metaFilename));
102
    }
103 1
    $result = $resolver->resolve($meta);
104 1
    foreach($this->metaNormalizers as $normalizer) {
105 1
      $normalizer($result, $html, $filename);
106
    }
107 1
    return $result;
108
  }
109
  
110
  protected function addAsset(string $asset): void {
111 1
    $asset = realpath($asset);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $asset. This often makes code more readable.
Loading history...
112 1
    if(!in_array($asset, $this->assets)) {
113 1
      $this->assets[] = $asset;
114
    }
115 1
  }
116
  
117
  protected function normalizeTitle(array &$meta, string &$html, string $filename): void {
2 ignored issues
show
introduced by
The method parameter $filename is never used
Loading history...
introduced by
Line exceeds 80 characters; contains 90 characters
Loading history...
Unused Code introduced by
The parameter $filename is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
118 1
    if(strlen($meta["title"]) === 0) {
119 1
      unset($meta["title"]);
120 1
      $html = str_replace("
121 1
  <title>%%title%%</title>", "", $html);
122
    }
123 1
  }
124
  
125 View Code Duplication
  protected function normalizeStyles(array &$meta, string &$html, string $filename): void {
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 91 characters
Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126 1
    $basePath = dirname($filename);
127 1
    $meta["styles"] = array_filter($meta["styles"], function($value) use($basePath) {
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 85 characters
Loading history...
128 1
      return file_exists("$basePath/$value");
129 1
    });
130 1
    if(!count($meta["styles"])) {
131 1
      unset($meta["styles"]);
132 1
      $html = str_replace("
133 1
  %%styles%%", "", $html);
134 1
      return;
135
    }
136 1
    array_walk($meta["styles"], function(&$value) use($basePath) {
137 1
      $this->addAsset("$basePath/$value");
138 1
      $value = "<link rel=\"stylesheet\" type=\"text/css\" href=\"$value\">";
139 1
    });
140 1
    $meta["styles"] = implode("\n  ", $meta["styles"]);
141 1
  }
142
  
143 View Code Duplication
  protected function normalizeScripts(array &$meta, string &$html, string $filename): void {
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 92 characters
Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144 1
    $basePath = dirname($filename);
145 1
    $meta["scripts"] = array_filter($meta["scripts"], function($value) use($basePath) {
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 87 characters
Loading history...
146 1
      return file_exists("$basePath/$value");
147 1
    });
148 1
    if(!count($meta["scripts"])) {
149 1
      unset($meta["scripts"]);
150 1
      $html = str_replace("
151 1
  %%scripts%%", "", $html);
152 1
      return;
153
    }
154 1
    array_walk($meta["scripts"], function(&$value) use($basePath) {
155 1
      $this->addAsset("$basePath/$value");
156 1
      $value = "<script type=\"text/javascript\" src=\"$value\"></script>";
157 1
    });
158 1
    $meta["scripts"] = implode("\n  ", $meta["scripts"]);
159 1
  }
160
  
161
  protected function createHtml(string $filename): string {
162 1
    $parser = new GithubMarkdown();
163 1
    $parser->html5 = $parser->keepListStartNumber = $parser->enableNewlines = true;
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 83 characters
Loading history...
164 1
    $source = $parser->parse(file_get_contents($filename));
165 1
    $html = file_get_contents($this->templateFile);
166 1
    if(substr($source, -1) === PHP_EOL) {
167 1
      $source = substr($source, 0, -1);
168
    }
169 1
    $html = str_replace("%%source%%", $source, $html);
170 1
    return $html;
171
  }
172
  
173
  /**
174
   * @internal
175
   */
176
  public function clearOutputFolder(): void {
177 1
    FileSystem::delete($this->output);
178 1
  }
179
  
180
  /**
181
   * @internal
182
   */
183
  public function copyAssets(): void {
184 1
    foreach($this->assets as $asset) {
185 1
      $path = str_replace($this->source, "", $asset);
186 1
      $target = "$this->output$path";
187 1
      FileSystem::copy($asset, $target);
188 1
      echo "Copied $path";
189
    }
190 1
  }
191
  
192
  /**
193
   * @internal
194
   */
195
  public function processImages(string $html, self $generator, string $filename): void {
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 88 characters
Loading history...
196 1
    $dom = new \DOMDocument();
197 1
    $dom->loadHTML($html);
198 1
    $images = $dom->getElementsByTagName("img");
199
    /** @var \DOMElement $image */
200 1
    foreach($images as $image) {
201 1
      $path = dirname($filename) . "/" . $image->getAttribute("src");
202 1
      if(file_exists($path)) {
203 1
        $generator->addAsset($path);
204
      }
205
    }
206 1
  }
207
  
208
  /**
209
   * Generate the site
210
   */
211
  public function generate(): void {
212 1
    $this->onBeforeGenerate();
213 1
    $files = Finder::findFiles("*.md")
214 1
      ->exclude("README.md")
215 1
      ->from($this->source)
216 1
      ->exclude("vendor", ".git", "tests");
217
    /** @var \SplFileInfo $file */
218 1
    foreach($files as $file) {
219 1
      $path = str_replace($this->source, "", dirname($file->getRealPath()));
220 1
      $html = $this->createHtml($file->getRealPath());
221 1
      $meta = $this->getMeta($file->getRealPath(), $html);
222 1
      foreach($meta as $key => $value) {
223 1
        $html = str_replace("%%$key%%", $value, $html);
224
      }
225 1
      $basename = $file->getBasename(".md") . ".html";
226 1
      $filename = "$this->output$path/$basename";
227 1
      FileSystem::write($filename, $html);
228 1
      echo "Created $path/$basename\n";
229 1
      $this->onCreatePage($html, $this, $file->getRealPath());
230
    }
231 1
    $this->onAfterGenerate();
232 1
  }
233
}
234
?>