Completed
Push — master ( 2c4826...e78d31 )
by Angus
02:45
created

Spritesheet::generate()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 17
nc 2
nop 0
dl 0
loc 25
rs 8.8571
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
const ASSET_FOLDER = 'public/assets';
7
const ICON_FOLDER  = ASSET_FOLDER.'/img/site_icons';
8
9
10
class Spritesheet {
11
	private $fileList;
12
	private $less;
13
14
	public function __construct() {
15
		$this->fileList = $this->getFileList();
16
		$this->less     = "";
17
	}
18
19
	public function generate() {
20
		$width = (count($this->fileList) * (16 + /* padding */ 2)) - 2;
21
22
		$sheetImage = imagecreatetruecolor($width, 16);
23
		imagealphablending($sheetImage, FALSE);
24
		imagesavealpha($sheetImage, TRUE);
25
26
		imagefill($sheetImage,0,0,0x7fff0000);
27
28
		$x = 0;
29
		foreach ($this->fileList as $filename) {
30
			$siteImage = imagecreatefrompng(ICON_FOLDER. "/{$filename}");
31
			imagealphablending($siteImage, TRUE);
32
33
			$dst_x = ((16 + 2) * $x);
34
			imagecopyresampled($sheetImage, $siteImage, $dst_x, 0, 0, 0, 16, 16, 16, 16);
35
36
			$this->generateLESS($filename, $dst_x);
37
			$x++;
38
		}
39
40
		imagepng($sheetImage, ASSET_FOLDER."/img/sites.png");
41
		say("Updates spritesheet!");
42
		$this->modifySiteLESS();
43
	}
44
	private function generateLESS(string $filename, int $dst_x) {
45
		$parts = pathinfo($filename);
46
47
		$this->less .= "\n".
48
			"	&.sprite-{$parts['filename']} {\n".
49
			"		.stitches-sprite(-{$dst_x}px);\n".
50
			"	}\n";
51
	}
52
	private function modifySiteLESS() {
53
		$newSiteLESS = trim($this->less);
54
55
		$icons_file = ASSET_FOLDER.'/less/modules/icons.less';
56
		$oldLESS = file_get_contents($icons_file);
57
		if(preg_match('/\.sprite-site.*\@cache-version: ([0-9]+);/s', $oldLESS, $cvMatches)) {
58
			$cacheVersion = ((int) $cvMatches[1]) + 1;
59
60
			$newLESS = preg_replace('/\.sprite-site.*/s', '',$oldLESS);
61
			$newLESS .= ''.
62
				".sprite-site {\n".
63
				"	.sprite();\n".
64
				"	@cache-version: {$cacheVersion};\n".
65
				"	background: url('../../img/sites.@{cache-version}.png') no-repeat;\n\n".
66
				"	{$newSiteLESS}\n".
67
				"}\n";
68
69
			file_put_contents($icons_file, $newLESS);
70
			say("Updated LESS!");
71
		} else {
72
			die("Can't find cache-version?");
73
		}
74
	}
75
76
	private function getFileList() : array {
77
		return array_diff(scandir(ICON_FOLDER), array('..', '.'));
78
	}
79
}
80
function say(string $text = "") { print "{$text}\n"; }
81
82
$Spritesheet = new Spritesheet();
83
$Spritesheet->generate();
84