Advertisement
stuppid_bot

PHP class generation with JavaScript in the console

Oct 19th, 2016
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Генерация PHP класса
  2. ((className, props, useCamelCase) => {
  3.   var names = props.split(/,\s*/);
  4.   var tab = '  ';
  5.   var ths = '$this->';
  6.   var pubfunc = 'public function ';
  7.   var constructorArgs = [];
  8.   var lines = ['/**', ' * Description goes here', ' */',
  9.     'class ' + className + ' {'];
  10.   var lines2 = [];
  11.   var lines3 = [tab + '// Getters', ''];
  12.   var lines4 = [tab + '// Setters', ''];
  13.   names.forEach((name) => {
  14.     var varName = '$' + name;
  15.     constructorArgs.push(varName);
  16.     lines.push(tab + 'protected ' + varName + ';');
  17.     var setName = 'set' +
  18.       (useCamelCase ? name.slice(0, 1).toUpperCase() + name.slice(1) :
  19.         '_' + name);
  20.     lines2.push(tab + tab + ths + setName + '(' + varName + ');');
  21.     lines3.push(tab + pubfunc + name + '() {');
  22.     lines3.push(tab + tab + 'return ' + ths + name + ';');
  23.     lines3.push(tab + '}');
  24.     lines3.push('');
  25.     lines4.push(tab + pubfunc + setName + '(' + varName + ') {');
  26.     // lines4.push(tab + tab + 'if (0) {');
  27.     // lines4.push(tab + tab + tab +
  28.     //   "throw new InvalidArgumentException('Invalid " + name + "');");
  29.     // lines4.push(tab + tab + '}')
  30.     lines4.push(tab + tab + ths + name + ' = ' + varName + ';');
  31.     lines4.push(tab + '}');
  32.     lines4.push('');
  33.   });
  34.   lines.push('');
  35.   lines.push(tab + pubfunc + '__construct(' + constructorArgs.join(', ') +
  36.     ') {');
  37.   lines = lines.concat(lines2);
  38.   lines.push(tab + '}');
  39.   lines.push('');
  40.   lines = lines.concat(lines3);
  41.   lines = lines.concat(lines4.slice(0, -1));
  42.   lines.push('}');
  43.   lines.push('');
  44.   var str = lines.join('\n');
  45.   console.log(str);
  46.   prompt('Ctrl+C:', str);
  47. })(
  48.   'Test',
  49.   'foo, bar, baz',
  50.   true
  51. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement