-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuibuilder.php
More file actions
executable file
·656 lines (568 loc) · 21.7 KB
/
uibuilder.php
File metadata and controls
executable file
·656 lines (568 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
#!/usr/bin/php -d display_errors
<?php
$dir = dirname(realpath(__FILE__));
define('INST_PATH', exec('pwd').'/');
set_include_path(
'/etc/dumbophp'.PATH_SEPARATOR.
'/etc/dumbophp/bin'.PATH_SEPARATOR.
INST_PATH.PATH_SEPARATOR.
INST_PATH.'bin'.PATH_SEPARATOR.
INST_PATH.'lib'.PATH_SEPARATOR.
get_include_path().PATH_SEPARATOR.
PEAR_EXTENSION_DIR.PATH_SEPARATOR.
'/windows/dumbophp'.PATH_SEPARATOR.
'/windows/dumbophp/bin'.PATH_SEPARATOR.
'/windows/system32/dumbophp'.PATH_SEPARATOR.
'/windows/system32/dumbophp/bin'.PATH_SEPARATOR.
INST_PATH.'DumboPHP'
);
function Camelize($params, &$obj = null) {
if ($obj === null):
$string = $params;
else:
$string = $params[0];
endif;
$newName = "";
if (preg_match("[-]", $string)):
$names = preg_split("[-]", $string);
$i = 1;
foreach ($names as $single):
$newName .= ucfirst($single);
$i++;
endforeach;
else:
$newName .= ucfirst($string);
endif;
return $newName;
}
class generatorException extends Exception {}
class JSMin {
private $_code = '';
private $identifiers = [];
private $counter = 0;
public function __construct($code) {
$this->_code = $code;
}
public function min() {
if (preg_match_all('/^\b(var|let|const|function)\s+([a-zA-Z_\$][a-zA-Z0-9_\$]*)/', $this->_code, $matches)) {
foreach($matches[2] as $identifier) {
if (!isset($this->identifiers[$identifier])) {
$this->identifiers[$identifier] = $this->_nextName();
}
}
$this->_code = strtr($this->_code, $this->identifiers);
}
foreach ($this->identifiers as $original => $obfuscated) {
$this->_code = preg_replace('/\b' . $original . '\b/', $obfuscated, $this->_code);
}
return $this->_code;
}
private function _nextName() {
$name = '';
$num = $this->counter;
do {
$name = chr($num % 26 + 97) . $name;
$num = floor($num / 26) - 1;
} while ($num >= 0);
$this->counter++;
return $name;
}
}
class UIGenerator {
private $_path = '';
private $_dumboJsDirectiveImportHeader = '';
private $_mainConfig = null;
private $_dmbSRC = '';
public function __construct($path) {
$this->_mainConfig = json_decode(file_get_contents('./dumbojs.conf.json'));
$this->_dmbSRC = $this->_mainConfig->src;
$this->_path = $path;
$this->_dumboJsDirectiveImportHeader =<<<DUMBO
import { DumboDirective } from '{$this->_dmbSRC}dumbo.min.js';
DUMBO;
}
public function component($name) {
$componentsPath = "{$this->_path}components/{$name}";
$sourceJS = "{$name}.directive.js";
$testJS = "{$name}.directive.spec.js";
$sass = "{$name}.scss";
$camelizedName = Camelize($name);
if(!mkdir($componentsPath)):
throw new generatorException("Cannot create component directory: {$componentsPath}");
endif;
$directiveContent = <<<DUMBO
\n{$this->_dumboJsDirectiveImportHeader}
export class {$camelizedName} extends DumboDirective {
static selector = '{$name}';
constructor() {
super();
}
init () {
}
}
DUMBO;
$specContent = <<<DUMBO
import { DumboTestApp } from '{$this->_dmbSRC}dumbo.min.js';
import { {$camelizedName} } from './{$sourceJS}';
describe('{$camelizedName} Directive', () => {
let component = null;
let fixture = null;
DumboTestApp.setComponents([
{$camelizedName}
]);
beforeEach(() => {
fixture = DumboTestApp.fixture({$camelizedName});
component = DumboTestApp.createComponent(fixture);
});
afterEach( done => {
component && component.remove();
done();
});
it('Should render component', () => {
expect(component).toBeDefined();
});
});
DUMBO;
$sassContent = <<<DUMBO
{$name} {
}
DUMBO;
file_put_contents("{$componentsPath}/{$sourceJS}", $directiveContent);
file_put_contents("{$componentsPath}/{$testJS}", $specContent);
file_put_contents("{$componentsPath}/{$sass}", $sassContent);
}
}
class UIBuilder {
public $shellOutput = true;
private $_colors = null;
private $_command = null;
private $_arguments = [];
private $_params = [];
private $_commands = [
'build',
'generate',
'test'
];
private $_options = [
'watch' => ['value' => false, 'cast' => 'boolean']
];
private $_specFiles = [];
private $_mainConfig = null;
public function __construct() {
require_once "/etc/dumbophp/lib/DumboShellColors.php";
$this->_colors = new DumboShellColors();
$this->_mainConfig = json_decode(file_get_contents('./dumbojs.conf.json'));
}
private function _logger($source, $message) {
if (empty($source) or empty($message) or !is_string($source) or !is_string($message)):
return false;
endif;
$logdir = INST_PATH.'tmp/logs/';
is_dir($logdir) or mkdir($logdir, 0777, true);
$file = "{$source}.log";
$stamp = date('d-m-Y i:s:H');
file_exists("{$logdir}{$file}")
and filesize("{$logdir}{$file}") >= 524288000
and rename("{$logdir}{$file}", "{$logdir}{$stamp}_{$file}");
$this->shellOutput and fwrite(STDOUT, "{$message}\n");
file_put_contents("{$logdir}{$file}", "[{$stamp}] - {$message}\n", FILE_APPEND);
return true;
}
private function _readFiles($path, $pattern, $goUnder = true) {
$files = [];
$dir = opendir($path);
//first level, not subdirectories
while(false !== ($file = readdir($dir))):
$file !== '.'
and $file !== '..'
and is_file("{$path}{$file}")
and preg_match($pattern, $file, $matches) === 1
and ($files[] = "{$path}{$file}");
endwhile;
closedir($dir);
//Second level, subdirectories
if ($goUnder):
$dir = opendir($path);
while(false !== ($file = readdir($dir))):
$npath = "{$path}{$file}";
if ($file !== '.' and $file !== '..' and is_dir($npath) and is_readable($npath)):
$dir1 = opendir("{$path}{$file}");
if(false !== $dir1):
while(false !== ($file1 = readdir($dir1))):
is_file("{$path}{$file}/{$file1}")
and preg_match($pattern, $file1, $matches) === 1
and ($files[] = "{$path}{$file}/{$file1}");
endwhile;
closedir($dir1);
endif;
endif;
endwhile;
closedir($dir);
endif;
sort($files);
return $files;
}
private function _parseOptions() {
$trueFalse = ['true' => true, 'false' => false];
foreach($this->_arguments as $i => $arg) {
preg_match('@\-\-([a-zA-Z0-9]+)\=([a-z0-9\-\_\/]+)[\s]*@im', $arg, $match);
if (sizeof($match) === 3) {
if(isset($this->_options[$match[1]])){
switch($this->_options[$match[1]]['cast']) {
case 'numeric':
$match[2] = (integer)$match[2];
break;
case 'boolean':
$match[2] = $trueFalse[strtolower($match[2])];
break;
case 'string':
$match[2] = trim((string)$match[2]);
break;
default:
throw new Exception("Value not allowed for {$match[1]}");
break;
}
$this->_options[$match[1]]['value'] = strlen($match[2]) > 0 ? $match[2] : null;
}
$this->_arguments[$i] = null;
unset($this->_arguments[$i]);
}
}
}
private function _cleanJS($code) {
$pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\')\/\/.*))/';
$code = preg_replace($pattern, '', $code);
$search = [
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/<!--(.|\s)*?-->/', // Remove HTML comments
'/\s*([{};,:=()+\-*\/<>])\s*/' // remove spaces around operators
];
$replace = [
'>',
'<',
'\\1',
'',
'$1'
];
return preg_replace($search, $replace, $code);
}
private function _cleanHTML($code) {
$search = [
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/<!--(.|\s)*?-->/' // Remove HTML comments
];
$replace = [
'>',
'<',
''
];
return preg_replace($search, $replace, $code);
}
private function _setImport(string $content): string {
return str_replace('../dumbo.js', './dumbo.min.js', $content);
}
public function sassAction() {
$sass = new Sass();
$sass->setStyle(Sass::STYLE_COMPRESSED);
$files = $this->_readFiles(INST_PATH.'src/', '/(.+)\.scss/');
array_unshift($files, INST_PATH.'src/styles.scss');
$bigFile = '';
if(sizeof($files) > 0):
while (null !== ($file = array_shift($files))):
$bigFile .= file_get_contents($file)."\n";
endwhile;
endif;
$css = $sass->compile($bigFile);
file_put_contents(INST_PATH.'dist/styles.css', $css);
}
public function setspecsAction() {
$files = $this->_readFiles(INST_PATH.$this->_mainConfig->src, '/^(?=.*\.spec).+\.js$/');
$this->_specFiles = [];
if(sizeof($files) > 0):
while (null !== ($file = array_shift($files))):
$this->_specFiles[] = str_replace(INST_PATH, '/', $file);
endwhile;
endif;
}
public function setComponents() {
$filesjs = $this->_readFiles(INST_PATH."src/", '/(.+)\.js/');
$fileContent = '';
if(sizeof($filesjs) > 0):
while (null !== ($file = array_shift($filesjs))):
$name = basename($file);
$fileContent = file_get_contents($file);
$fileContent = $this->_cleanJS($fileContent);
$fileContent = $this->_setImport($fileContent);
file_put_contents(INST_PATH."dist/{$name}", $fileContent);
endwhile;
endif;
}
public function setTemplates() {
$files = $this->_readFiles(INST_PATH."src/", '/(.+)\.html$/');
$fileContent = '';
if(sizeof($files) > 0):
while (null !== ($file = array_shift($files))):
$name = basename($file);
$fileContent = file_get_contents($file);
$fileContent = $this->_cleanHTML($fileContent);
file_put_contents(INST_PATH."dist/{$name}", $fileContent);
endwhile;
endif;
}
public function setIndexes() {
$directives = $this->_readFiles(INST_PATH."dist/", '/^(?=.*\.directive).+\.js$/');
$factories = $this->_readFiles(INST_PATH."dist/", '/^(?=.*\.factory).+\.js$/');
$includes = [];
if(sizeof($directives) > 0):
while (null !== ($file = array_shift($directives))):
$includes[] = "export * from './".basename($file)."';";
endwhile;
endif;
file_put_contents(INST_PATH.'dist/directives.js', implode("\n",$includes));
$includes = [];
if(sizeof($factories) > 0):
while (null !== ($file = array_shift($factories))):
$includes[] = "export * from './".basename($file)."';";
endwhile;
endif;
file_put_contents(INST_PATH.'dist/factories.js', implode("\n",$includes));
}
public function minifyDumbo() {
$code = file_get_contents(INST_PATH.$this->_mainConfig->src.'dumbo.js');
$code = $this->_cleanJS($code);
$jsmin = new JSMin($code);
$minified = $jsmin->min();
file_put_contents(INST_PATH.'dist/dumbo.min.js', $minified);
}
public function buildUIAction() {
$this->_logger('dumbo_ui_builder', 'Building files...');
$start = microtime(true);
// $this->sassAction();
// $this->setComponents();
// $this->setTemplates();
// $this->setIndexes();
$this->minifyDumbo();
// $this->setTestPageAction();
// $this->_options['watch']['value'] && $this->watchUIAction();
$total = microtime(true) - $start;
$this->_logger('dumbo_ui_builder', "Jobs finished, took {$total} seconds.");
}
public function setTestPageAction() {
$this->_logger('dumbo_ui_builder', 'Building test files...');
$this->setspecsAction();
$specs = '';
while(null !== ($file = array_shift($this->_specFiles))):
$specs =<<<DUMBO
{$specs}
<script src="{$file}" type="module"></script>
DUMBO;
endwhile;
$page = <<<DUMBO
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Dumbo UI tests</title>
<link rel="preconnect" href="./">
<link rel="stylesheet" type="text/css" href="jasmine/jasmine.css">
<link rel="stylesheet" type="text/css" href="dist/styles.css">
<link rel="preload" as="style" type="text/css" href="dist/styles.css">
</head>
<body>
<div class="html-reporter">
<div class="banner">
</div>
<ul class="symbol-summary"></ul>
<div class="alert">
</div>
<div class="results">
</div>
</div>
<div id="components">
</div>
<script src="jasmine/jasmine.js" type="text/javascript"></script>
<script src="jasmine/jasmine-html.js" type="text/javascript"></script>
<script src="jasmine/jasmine-boot.js" type="text/javascript"></script>
{$specs}
</body>
</html>
DUMBO;
file_put_contents(INST_PATH.'tests/test.html',$page);
}
public function testUIAction() {
$this->buildUIAction();
$descriptorsserver = [
['pipe', 'r'],
['pipe', 'w'],
['file', '/tmp/error-output.txt', 'a'],
];
$cwd = './app/webroot/';
$env = [];
$processServer = proc_open('php -S localhost:3456', $descriptorsserver, $pipeserver, $cwd, $env);
$descriptorspec = [
['pipe', 'r'],
['pipe', 'w'],
['file', '/tmp/error-output.txt', 'a'],
];
$pathToComponents = 'file://' .INST_PATH. 'app/webroot/';
$command =<<<DUMBO
/home/rantes/chromium/chrome \\
--headless \\
--disable-gpu \\
--repl \\
--run-all-compositor-stages-before-draw \\
--virtual-time-budget=10000 \\
http://localhost:3456/test.html
DUMBO;
$process = proc_open($command, $descriptorspec, $pipes, $cwd, $env);
if(is_resource($process)):
$script = <<<DUMBO
let results = document.querySelector('.jasmine_html-reporter'), duration = results.querySelector('.jasmine-duration'), overall = results.querySelector('.jasmine-overall-result'), data = `\${duration.innerHTML} - \${overall.innerText}`; data;
DUMBO;
fwrite($pipes[0], $script);
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$rvalue = proc_close($process);
if(is_resource($processServer)):
fclose($pipeserver[0]);
fclose($pipeserver[1]);
proc_terminate($processServer);
endif;
if ($rvalue === 0):
preg_match('@(exceptionDetails)@i', $output, $matches);
if (empty($matches)):
$output = str_replace('>>>', '', $output);
$output = trim($output);
$result = json_decode($output)->result;
preg_match('@((?:\d)+)\sfailures@', $result->value, $matches);
$errors = !empty($matches);
$this->_logger('dumbo_ui_unit_testing', $result->value);
(bool)$errors and fwrite(STDERR, "{$matches[0]}\n");
else:
$this->showError("Exception happened: {$output}");
endif;
else:
$this->showError('Oops! something happened!');
endif;
endif;
}
private function help() {
$text = <<<DUMBO
▓█████▄ █ ██ ███▄ ▄███▓ ▄▄▄▄ ▒█████
▒██▀ ██▌ ██ ▓██▒▓██▒▀█▀ ██▒▓█████▄ ▒██▒ ██▒
░██ █▌▓██ ▒██░▓██ ▓██░▒██▒ ▄██▒██░ ██▒
░▓█▄ ▌▓▓█ ░██░▒██ ▒██ ▒██░█▀ ▒██ ██░
░▒████▓ ▒▒█████▓ ▒██▒ ░██▒░▓█ ▀█▓░ ████▓▒░
▒▒▓ ▒ ░▒▓▒ ▒ ▒ ░ ▒░ ░ ░░▒▓███▀▒░ ▒░▒░▒░
░ ▒ ▒ ░░▒░ ░ ░ ░ ░ ░▒░▒ ░ ░ ▒ ▒░
░ ░ ░ ░░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒
░ ░ ░ ░ ░ ░
░ ░
DumboPHP 2.0 by Rantes
DumboUI shell.
Ussage:
dumbo <command> <option> <params>
Commands:
build
Builds the UI components
Options:
--watch=[true|false] Set a daemon to watch files (used in tests)
generate [component] <name>
Generates scripts for component.
DUMBO;
fwrite(STDOUT, $text . "\n");
}
public function watchUIAction() {
$this->_logger('dumbo_ui_watcher', 'Setting up files for watch...');
$files = new ArrayObject();
$list = [
...$this->_readFiles(INST_PATH.$this->_mainConfig->src, '/(.+)\.scss/', false),
...$this->_readFiles(INST_PATH.$this->_mainConfig->src, '/^(.+)\.js$/'),
];
$this->_logger('dumbo_ui_watcher', "Watching for changes in files: \n".implode("\n", $list));
foreach($list as $file):
$stats = stat($file);
$files[] = ['path'=> $file, 'mtime' => $stats['mtime']];
endforeach;
$this->_logger('dumbo_ui_watcher', 'Watching files...');
while(true):
foreach($files as $index => $file):
$stats = stat($file['path']);
if($stats['size'] > 0 and $file['mtime'] !== $stats['mtime']):
$this->_logger('dumbo_ui_watcher', "File changed {$file['path']}");
$files[$index]['mtime'] = $stats['mtime'];
$this->_logger('dumbo_ui_watcher', 'Runing tasks...');
$start = microtime(true);
$this->sassAction();
$this->setTestPageAction();
$total = microtime(true) - $start;
$this->_logger('dumbo_ui_watcher', "Jobs finished, took {$total} seconds.");
break;
endif;
endforeach;
endwhile;
}
public function showError($errorMessage) {
fwrite(STDOUT, $this->_colors->getColoredString($errorMessage, "white", "red") . "\n");
}
public function showMessage($errorMessage) {
fwrite(STDOUT, $this->_colors->getColoredString($errorMessage, "white", "green") . "\n");
}
public function showNotice($errorMessage) {
fwrite(STDOUT, $this->_colors->getColoredString($errorMessage, "blue", "yellow") . "\n");
}
private function generateScripts() {
if(empty($this->_arguments[0]) && sizeof($this->_arguments) < 2) {
$this->help();
die('Error: Missing params.');
}
for ($i=1; $i < sizeof($this->_arguments); $i++) {
$this->_params[] = $this->_arguments[$i];
}
$generator = new UIGenerator(INST_PATH.'ui-components/');
switch ($this->_arguments[0]) {
case 'component':
$this->showNotice('Creating scaffold for "'.$this->_arguments[1].'".');
$generator->component($this->_arguments[1]);
break;
default:
$this->help();
die('Option no valid for generate.');
break;
}
}
public function run($argv) {
if(empty($argv[1])):
$this->help();
die('Error: Option not valid.');
endif;
array_shift($argv);
$this->_command = array_shift($argv);
$this->_arguments = $argv;
$this->_parseOptions();
if(in_array($this->_command, $this->_commands)):
switch($this->_command):
case 'generate':
$this->generateScripts();
break;
case 'test':
$this->testUIAction();
break;
case 'build':
default:
$this->buildUIAction();
break;
endswitch;
else:
$this->help();
die('Error: Option not valid.');
endif;
}
}
$builder = new UIBuilder();
$builder->run($argv);