Completed
Push — master ( 7e7429...42c63f )
by Jakub
01:50
created

Generator::processAssets()   C

Complexity

Conditions 7
Paths 20

Size

Total Lines 35
Code Lines 25

Duplication

Lines 14
Ratio 40 %

Code Coverage

Tests 29
CRAP Score 7

Importance

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