Passed
Push — master ( 42c63f...308939 )
by Jakub
01:44
created

Generator::getSource()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
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
 */
20 1
class Generator {
21 1
  use \Nette\SmartObject;
22
  
23
  /** @var string */
24
  protected $source;
25
  /** @var string */
26
  protected $output;
27
  /** @var string[] */
28
  protected $assets = [];
29
  
30
  public function __construct(string $source, string $output) {
31 1
    $this->setSource($source);
32 1
    FileSystem::createDir($output);
33 1
    $this->setOutput($output);
34 1
  }
35
  
36
  public function getSource(): string {
37 1
    return $this->source;
38
  }
39
  
40
  public function setSource(string $source) {
41 1
    if(is_dir($source)) {
42 1
      $this->source = realpath($source);
43
    }
44 1
  }
45
  
46
  public function getOutput(): string {
47 1
    return $this->output;
48
  }
49
  
50
  public function setOutput(string $output) {
51 1
    $this->output = realpath($output);
52 1
  }
53
  
54
  protected function getMeta(string $filename): array {
55 1
    $resolver = new OptionsResolver();
56 1
    $resolver->setDefaults([
57 1
      "title" => "",
58
      "styles" => [],
59
      "scripts" => [],
60
    ]);
61 1
    $isArrayOfStrings = function(array $value) {
62 1
      return Validators::everyIs($value, "string");
63
    };
64 1
    $resolver->setAllowedTypes("title", "string");
65 1
    $resolver->setAllowedTypes("styles", "array");
66 1
    $resolver->setAllowedValues("styles", $isArrayOfStrings);
67 1
    $resolver->setAllowedTypes("scripts", "array");
68 1
    $resolver->setAllowedValues("scripts", $isArrayOfStrings);
69 1
    $metaFilename = str_replace(".md", ".neon", $filename);
70 1
    $meta = [];
71 1
    if(file_exists($metaFilename)) {
72 1
      $meta = Neon::decode(file_get_contents($metaFilename));
73
    }
74 1
    return $resolver->resolve($meta);
75
  }
76
  
77
  protected function addAsset(string $asset): void {
78 1
    if(!in_array($asset, $this->assets)) {
79 1
      $this->assets[] = realpath($asset);
80
    }
81 1
  }
82
  
83
  protected function processAssets(array &$meta, string &$html, string $basePath): void {
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 89 characters
Loading history...
84 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...
85 1
      return file_exists("$basePath/$value");
86 1
    });
87 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...
88 1
      return file_exists("$basePath/$value");
89 1
    });
90 1
    if(!count($meta["styles"])) {
91 1
      unset($meta["styles"]);
92 1
      $html = str_replace("
93 1
  %%styles%%", "", $html);
94
    }
95 1
    if(!count($meta["scripts"])) {
96 1
      unset($meta["scripts"]);
97 1
      $html = str_replace("
98 1
  %%scripts%%", "", $html);
99
    }
100 1
    if(!isset($meta["styles"]) AND !isset($meta["scripts"])) {
101 1
      return;
102
    }
103 1 View Code Duplication
    if(isset($meta["styles"])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
104 1
      array_walk($meta["styles"], function(&$value) use($basePath) {
105 1
        $this->addAsset("$basePath/$value");
106 1
        $value = "<link rel=\"stylesheet\" type=\"text/css\" href=\"$value\">";
107 1
      });
108 1
      $meta["styles"] = implode("\n  ", $meta["styles"]);
109
    }
110 1 View Code Duplication
    if(isset($meta["scripts"])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
111 1
      array_walk($meta["scripts"], function(&$value) use($basePath) {
112 1
        $this->addAsset("$basePath/$value");
113 1
        $value = "<script type=\"text/javascript\" src=\"$value\"></script>";
114 1
      });
115 1
      $meta["scripts"] = implode("\n  ", $meta["scripts"]);
116
    }
117 1
  }
118
  
119
  protected function createHtml(string $filename): string {
120 1
    $parser = new GithubMarkdown();
121 1
    $parser->html5 = $parser->keepListStartNumber = $parser->enableNewlines = true;
0 ignored issues
show
introduced by
Line exceeds 80 characters; contains 83 characters
Loading history...
122 1
    $source = $parser->parse(file_get_contents($filename));
123 1
    $meta = $this->getMeta($filename);
124 1
    $html = file_get_contents(__DIR__ . "/template.html");
125 1
    if(substr($source, -1) === PHP_EOL) {
126 1
      $source = substr($source, 0, -1);
127
    }
128 1
    if(strlen($meta["title"]) === 0) {
129 1
      unset($meta["title"]);
130 1
      $html = str_replace("
131 1
  <title>%%title%%</title>", "", $html);
132
    }
133 1
    $this->processAssets($meta, $html, dirname($filename));
134 1
    $meta["source"] = $source;
135 1
    foreach($meta as $key => $value) {
136 1
      $html = str_replace("%%$key%%", $value, $html);
137
    }
138 1
    return $html;
139
  }
140
  
141
  protected function copyAssets(): void {
142 1
    foreach($this->assets as $asset) {
143 1
      $path = str_replace($this->source, "", $asset);
144 1
      $target = "$this->output$path";
145 1
      FileSystem::copy($asset, $target);
146 1
      echo "Copied $path";
147
    }
148 1
  }
149
  
150
  /**
151
   * Generate the site
152
   */
153
  public function generate(): void {
154 1
    FileSystem::delete($this->output);
155 1
    $files = Finder::findFiles("*.md")
156 1
      ->exclude("README.md")
157 1
      ->from($this->source)
158 1
      ->exclude("vendor", ".git", "tests");
159
    /** @var \SplFileInfo $file */
160 1
    foreach($files as $file) {
161 1
      $path = str_replace($this->source, "", dirname($file->getRealPath()));
162 1
      $html = $this->createHtml($file->getRealPath());
163 1
      $basename = $file->getBasename(".md") . ".html";
164 1
      $filename = "$this->output$path/$basename";
165 1
      FileSystem::write($filename, $html);
166 1
      echo "Created $path/$basename\n";
167
    }
168 1
    $this->copyAssets();
169 1
  }
170
}
171
?>