Completed
Push — master ( 7338a5...b104f9 )
by Angus
03:05
created

FoolSlideGenerator::updateUserscript()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 56
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 26
nc 2
nop 0
dl 0
loc 56
rs 9.7251
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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