Completed
Push — master ( b10a9a...47a165 )
by Angus
02:58
created

FoolSlideGenerator::generateIcon()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 0
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
if(!extension_loaded('gd')) die('GD ext is required to run this!');
4
5
chdir(dirname(__FILE__).'/../'); //Just to make things easier, change dir to project root.
6
7
class FoolSlideGenerator {
8
	private $baseURL;
9
	private $className;
10
11
	public function __construct() {
12
		if(isset($_SERVER['argv']) && count($_SERVER['argv']) === 3){
13
			$this->baseURL   = rtrim($_SERVER['argv'][1], '/');
14
			$this->className = $_SERVER['argv'][2];
15
16
			if(!$this->testURL()) { die('URL returning non-200 status code.'); }
17
		} else {
18
			die('Args not valid?');
19
		}
20
	}
21
22
	public function generate() : void {
23
		$this->generateIcon();
24
25
		$this->generateModel();
26
		$this->generateTest();
27
28
		$this->updateUserscript();
29
30
		$this->updateDocs();
31
	}
32
33
	public function generateIcon() : void {
34
		$parse = parse_url($this->baseURL);
35
36
		if($icon = file_get_contents('https://www.google.com/s2/favicons?domain='.$parse['scheme'].'://'.$parse['host'])) {
37
			file_put_contents('./public/assets/img/site_icons/'.str_replace('.', '-', $parse['host']).'.png', $icon);
38
39
			system('php _scripts/generate_spritesheet.php'); //This is bad?
40
		} else {
41
			die("No favicon found?");
42
		}
43
	}
44
45
	public function generateModel() : void {
46
		$baseFile = file_get_contents('./application/models/Tracker/Sites/HelveticaScans.php');
47
48
		//Replace class name
49
		$baseFile = str_replace('class HelveticaScans', "class {$this->className}", $baseFile);
50
51
		//Replace baseURL
52
		$baseFile = str_replace('http://helveticascans.com/r', $this->baseURL, $baseFile);
53
54
		file_put_contents("./application/models/Tracker/Sites/{$this->className}.php", $baseFile);
55
	}
56
	public function generateTest() : void {
57
		$baseFile = file_get_contents('./application/tests/models/Tracker/Sites/HelveticaScans_test.php');
58
59
		//Replace class names
60
		$baseFile = str_replace('class HelveticaScans', "class {$this->className}", $baseFile);
61
		$baseFile = str_replace('coversDefaultClass HelveticaScans', "coversDefaultClass {$this->className}", $baseFile);
62
63
		//Replace tests
64
		$titleList  = $this->getTitles();
65
		$lengths = array_map('strlen', array_keys($titleList));
66
		$max_length = max($lengths) + 2;
67
		$testString = '';
68
		foreach($titleList as $stub => $name) {
69
			$stub = str_replace('\'', '\\\'', $stub);
70
			$name = str_replace('\'', '\\\'', $name);
71
72
			$testString .= "\t\t\t".str_pad("'{$stub}'", $max_length)." => '{$name}',\r\n";
73
		}
74
		$testString = rtrim($testString, ",\n");
75
76
		$baseFile = preg_replace('/\$testSeries.*\]/s', "\$testSeries = [\r\n{$testString}\r\n\t\t]", $baseFile);
77
78
		file_put_contents("./application/tests/models/Tracker/Sites/{$this->className}_test.php", $baseFile);
79
	}
80
81
	public function updateUserscript() : void {
82
		$baseFile = file_get_contents('./public/userscripts/manga-tracker.user.js');
83
84
		$parse = parse_url($this->baseURL);
85
		if(strpos($baseFile, $parse['host']) !== false) die("Domain already exists in userscript?");
86
87
		preg_match('/\@updated      ([0-9\-]+)\r.*?\@version      ([0-9\.]+)/s', $baseFile, $matches);
88
89
		//Add @include
90
		$include = '// @include      /^'.str_replace('https', 'https?', preg_replace('/([\/\.])/', '\\\\$1', $this->baseURL)).'\/read\/.*?\/[a-z]+\/[0-9]+\/[0-9]+(\/.*)?$/';
91
		$baseFile = str_replace('// @updated', "{$include}\r\n// @updated", $baseFile);
92
93
		//Update @updated
94
		$currentDate = date("Y-m-d", time());
95
		$baseFile = str_replace("@updated      {$matches[1]}","@updated      {$currentDate}", $baseFile);
96
97
		//Update @version
98
		$currentVersion = explode('.', $matches[2]);
99
		$newVersion = "{$currentVersion[0]}.{$currentVersion[1]}.". (((int) $currentVersion[2]) + 1);
100
		$baseFile = str_replace("@version      {$matches[2]}","@version      {$newVersion}", $baseFile);
101
102
		//Add site
103
		$siteData = <<<EOT
104
	/**
105
	 * {$this->className} (FoolSlide)
106
	 * @type {SiteObject}
107
	 */
108
	'{$parse['host']}' : extendSite({
109
		preInit : function(callback) {
110
			this.setupFoolSlide();
111
			callback();
112
		}
113
	}),
114
115
	//Tracking site
116
EOT;
117
		$baseFile = str_replace('	//Tracking site', $siteData, $baseFile);
118
119
		file_put_contents('./public/userscripts/manga-tracker.user.js', $baseFile);
120
121
		//Update .meta.js
122
		$baseFileMeta = file_get_contents('./public/userscripts/manga-tracker.meta.js');
123
		$baseFileMeta = str_replace("// @version      {$matches[2]}", "// @version      {$newVersion}", $baseFileMeta);
124
		file_put_contents('./public/userscripts/manga-tracker.meta.js', $baseFileMeta);
125
	}
126
127
	public function updateDocs() : void {
128
		$readmeFile = file_get_contents('./README.md');
129
		file_put_contents('./README.md', preg_replace('/(\s*)$/', "$1* {$this->className}$1", $readmeFile, 1));
130
131
		$helpFile = file_get_contents('./application/views/Help.php');
132
		file_put_contents('./application/views/Help.php', preg_replace('/(\s*<\/ul>)/', "\r\n\t\t<li>{$this->className}</li>$1", $helpFile));
133
134
		$changelogFile = file_get_contents('./public/CHANGELOG.md');
135
		$date = date("Y-m-d", time());
136
		if(strpos($changelogFile, $date) !== FALSE) {
137
			//Log already exists for current date.
138
			if(strpos($changelogFile, "[$date]\r\n### Added") !== FALSE) {
139
				$changelogFile = str_replace("[$date]\r\n### Added", "[$date]\r\n### Added\r\n- Added support for support for {$this->className}.", $changelogFile);
140
			} else {
141
				$changelogFile = str_replace("[$date]\r\n", "[$date]\r\n### Added\r\n- Added support for {$this->className}.\"", $changelogFile);
142
			}
143
		} else {
144
			//Log doesn't exist.
145
			$log = <<<EOT
146
## [{$date}]
147
### Added
148
- Support for {$this->className}.
149
EOT;
150
			$changelogFile = str_replace('All notable changes to this project will be documented in this file.', "All notable changes to this project will be documented in this file.\r\n\r\n{$log}", $changelogFile);
151
		}
152
153
		file_put_contents('./public/CHANGELOG.md', $changelogFile);
154
	}
155
156
	private function testURL() : bool {
157
		//https://stackoverflow.com/a/2280413/1168377
158
159
		$ch = curl_init("{$this->baseURL}/api/reader/chapters/orderby/desc_created/format/json");
160
161
		curl_setopt($ch, CURLOPT_NOBODY, true);
162
		curl_exec($ch);
163
		$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
164
		curl_close($ch);
165
166
		return $status_code === 200;
167
	}
168
	private function getTitles() : array {
169
		$titleArr = [];
170
171
		$jsonURL = "{$this->baseURL}/api/reader/comics/format/json";
172
		if($content = file_get_contents($jsonURL)) {
173
			$json = json_decode($content, TRUE);
174
			shuffle($json['comics']);
175
			$comics = array_slice($json['comics'], 0, 5, true);
176
177
			foreach($comics as $comic) {
178
				$titleArr[$comic['stub']] = $comic['name'];
179
			}
180
		}
181
182
		if(empty($titleArr)) die("API isn't returning any titles?");
183
		return $titleArr;
184
	}
185
}
186
function say(string $text = "") { print "{$text}\n"; }
187
188
$Generator = new FoolSlideGenerator();
189
$Generator->generate();
190