FoolSlideGenerator   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 188
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 188
rs 10
c 0
b 0
f 0
wmc 20
lcom 1
cbo 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 4
A generate() 0 15 1
A generateIcon() 0 15 3
A generateModel() 0 11 1
A generateTest() 0 24 2
B updateUserscript() 0 63 3
A updateDocs() 0 9 1
A testURL() 0 13 1
A getTitles() 0 17 4
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
		$domain =  preg_replace('#^https?://(.*?)(?:/.*?)?$#', '$1', $this->baseURL);
33
		say("\nAdmin SQL:");
34
		say("INSERT INTO `mangatracker_development`.`tracker_sites` (`id`, `site`, `site_class`, `status`, `use_custom`) VALUES (NULL, '{$domain}', '{$this->className}', 'enabled', 'Y');");
35
		say("INSERT INTO `mangatracker_production`.`tracker_sites` (`id`, `site`, `site_class`, `status`, `use_custom`) VALUES (NULL, '{$domain}', '{$this->className}', 'enabled', 'Y');");
36
	}
37
38
	public function generateIcon() : void {
39
		$parse = parse_url($this->baseURL);
40
41
		if(!file_exists('./public/assets/img/site_icons/'.str_replace('.', '-', $parse['host']).'.png')) {
42
			if($icon = file_get_contents('https://www.google.com/s2/favicons?domain='.$parse['scheme'].'://'.$parse['host'])) {
43
				file_put_contents('./public/assets/img/site_icons/'.str_replace('.', '-', $parse['host']).'.png', $icon);
44
45
				system('php _scripts/generate_spritesheet.php'); //This is bad?
46
			} else {
47
				die("No favicon found?");
48
			}
49
		} else {
50
			print "Icon already exists?\n";
51
		}
52
	}
53
54
	public function generateModel() : void {
55
		$baseFile = file_get_contents('./application/models/Tracker/Sites/HelveticaScans.php');
56
57
		//Replace class name
58
		$baseFile = str_replace('class HelveticaScans', "class {$this->className}", $baseFile);
59
60
		//Replace baseURL
61
		$baseFile = str_replace('https://helveticascans.com/r', $this->baseURL, $baseFile);
62
63
		file_put_contents("./application/models/Tracker/Sites/{$this->className}.php", $baseFile);
64
	}
65
	public function generateTest() : void {
66
		$baseFile = file_get_contents('./application/tests/models/Tracker/Sites/HelveticaScans_test.php');
67
68
		//Replace class names
69
		$baseFile = str_replace('class HelveticaScans', "class {$this->className}", $baseFile);
70
		$baseFile = str_replace('coversDefaultClass HelveticaScans', "coversDefaultClass {$this->className}", $baseFile);
71
72
		//Replace tests
73
		$titleList  = $this->getTitles();
74
		$lengths = array_map('strlen', array_keys($titleList));
75
		$max_length = max($lengths) + 2;
76
		$testString = '';
77
		foreach($titleList as $stub => $name) {
78
			$stub = str_replace('\'', '\\\'', $stub);
79
			$name = str_replace('\'', '\\\'', $name);
80
81
			$testString .= "\t\t\t".str_pad("'{$stub}'", $max_length)." => '{$name}',\r\n";
82
		}
83
		$testString = rtrim($testString, ",\n");
84
85
		$baseFile = preg_replace('/\$testSeries.*\]/s', "\$testSeries = [\r\n{$testString}\r\n\t\t]", $baseFile);
86
87
		file_put_contents("./application/tests/models/Tracker/Sites/{$this->className}_test.php", $baseFile);
88
	}
89
90
	public function updateUserscript() : void {
91
		$baseFileName = './public/userscripts/manga-tracker.user.js';
92
		$baseDomain   = 'trackr.moe';
93
		if(file_exists('./public/userscripts/manga-tracker.dev.user.js')) {
94
			$baseFileName = './public/userscripts/manga-tracker.dev.user.js';
95
			$baseDomain   = 'manga-tracker.localhost:20180';
96
		}
97
98
		$baseFile = file_get_contents($baseFileName);
99
100
		$parse = parse_url($this->baseURL);
101
		if(strpos($baseFile, $parse['host']) !== false) die("Domain already exists in userscript?");
102
103
		preg_match('/\@updated      ([0-9\-]+)[\r\n]+.*?\@version      ([0-9\.]+)/s', $baseFile, $matches);
104
105
		//Add @include
106
		$include = '// @include      /^'.str_replace('https', 'https?', preg_replace('/([\/\.])/', '\\\\$1', $this->baseURL)).'\/read\/.*?\/[a-z]+\/[0-9]+\/[0-9]+(\/.*)?$/';
107
		$baseFile = str_replace('// @updated', "{$include}\r\n// @updated", $baseFile);
108
109
		//Update @updated
110
		$currentDate = date("Y-m-d", time());
111
		$baseFile = str_replace("@updated      {$matches[1]}","@updated      {$currentDate}", $baseFile);
112
113
		//Update @version
114
		$currentVersion = explode('.', $matches[2]);
115
		$newVersion = "{$currentVersion[0]}.{$currentVersion[1]}.". (((int) $currentVersion[2]) + 1);
116
		$baseFile = str_replace("@version      {$matches[2]}","@version      {$newVersion}", $baseFile);
117
118
		//Add @require
119
		// @resource     fontAwesome
120
		$require = <<<EOT
121
// @require      https://{$baseDomain}/userscripts/sites/{$this->className}.1.js
122
// @resource     fontAwesome
123
EOT;
124
		$baseFile = str_replace('// @resource     fontAwesome', $require, $baseFile);
125
126
		file_put_contents($baseFileName, $baseFile);
127
128
		//Update .meta.js
129
		$baseFileMeta = file_get_contents('./public/userscripts/manga-tracker.meta.js');
130
		$baseFileMeta = str_replace("// @version      {$matches[2]}", "// @version      {$newVersion}", $baseFileMeta);
131
		file_put_contents('./public/userscripts/manga-tracker.meta.js', $baseFileMeta);
132
133
134
		// Create site js
135
		$siteData = <<<EOT
136
(function(sites) {
137
	/**
138
	 * {$this->className} (FoolSlide)
139
	 * @type {SiteObject}
140
	 */
141
	sites['{$parse['host']}'] = {
142
		preInit : function(callback) {
143
			this.setupFoolSlide();
144
			callback();
145
		}
146
	};
147
})(window.trackerSites = (window.trackerSites || {}));
148
149
EOT;
150
151
		file_put_contents("./public/userscripts/sites/{$this->className}.js", $siteData);
152
	}
153
154
	public function updateDocs() : void {
155
		$readmeFile = file_get_contents('./README.md');
156
		file_put_contents('./README.md', preg_replace('/(\s*)$/', "$1* {$this->className}$1", $readmeFile, 1));
157
158
		$helpFile = file_get_contents('./application/views/Help.php');
159
		file_put_contents('./application/views/Help.php', preg_replace('/(\r\n\t<\/ul> <!--ENDOFSITES-->)/', "\r\n\t\t<li>{$this->className}</li>$1", $helpFile));
160
161
		say("\nCHANGELOG must be edited manually as it now exists on the wiki!");
162
	}
163
164
	private function testURL() : bool {
165
		//https://stackoverflow.com/a/2280413/1168377
166
167
		$ch = curl_init("{$this->baseURL}/api/reader/chapters/orderby/desc_created/format/json");
168
169
		curl_setopt($ch, CURLOPT_NOBODY, true);
170
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
171
		curl_exec($ch);
172
		$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
173
		curl_close($ch);
174
175
		return $status_code === 200;
176
	}
177
	private function getTitles() : array {
178
		$titleArr = [];
179
180
		$jsonURL = "{$this->baseURL}/api/reader/comics/format/json";
181
		if($content = file_get_contents($jsonURL)) {
182
			$json = json_decode($content, TRUE);
183
			shuffle($json['comics']);
184
			$comics = array_slice($json['comics'], 0, 5, true);
185
186
			foreach($comics as $comic) {
187
				$titleArr[$comic['stub']] = $comic['name'];
188
			}
189
		}
190
191
		if(empty($titleArr)) die("API isn't returning any titles?");
192
		return $titleArr;
193
	}
194
}
195
function say(string $text = "") { print "{$text}\n"; }
196
197
$Generator = new FoolSlideGenerator();
198
$Generator->generate();
199