generate_entity_fields 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/local/bin/php
  2. <?php
  3. use Symfony\Component\Yaml\Yaml;
  4. define('ROOT', dirname(__DIR__));
  5. require ROOT . '/vendor/autoload.php';
  6. const types = [
  7. 'blob' => '',
  8. 'bool' => 'bool',
  9. 'char' => 'string',
  10. 'datetime' => '\DateTimeInterface',
  11. 'timestamp' => '\DateTimeInterface',
  12. 'html' => 'string',
  13. 'int' => 'int',
  14. 'numeric' => 'float',
  15. 'serial' => 'int',
  16. 'text' => 'string',
  17. 'varchar' => 'string',
  18. 'phone_number' => 'PhoneNumber',
  19. ];
  20. $path = Yaml::parseFile(ROOT . '/config/services.yaml')['services']['app.core.schemadef_driver']['arguments'][0];
  21. $path = str_replace('%kernel.project_dir%', ROOT, $path);
  22. $files = glob($path . '/*.php');
  23. foreach ($files as $file) {
  24. require_once $file;
  25. $declared = get_declared_classes();
  26. $class = end($declared);
  27. $no_ns_class = preg_replace('/.*?\\\\/', '', $class);
  28. $schema = $class::schemaDef();
  29. $fields = array_keys($schema['fields']);
  30. $fields_code = [];
  31. $methods_code = [];
  32. foreach ($fields as $field) {
  33. $nullable = !@$schema['fields'][$field]['not null'] ? '?' : '';
  34. $type = types[$schema['fields'][$field]['type']];
  35. $type = $type !== '' ? $nullable . $type : $type;
  36. $method_name = str_replace(' ', '', ucwords(str_replace('_', ' ', $field)));
  37. $default = @$schema['fields'][$field]['default'];
  38. if (isset($default) && $nullable != '?' && $type != '\DateTimeInterface') {
  39. if (is_string($default)) {
  40. $default = "'{$default}'";
  41. } elseif ($type == 'bool') {
  42. $default = $default ? 'true' : 'false';
  43. }
  44. $fields_code[] = " private {$type} \${$field} = {$default};";
  45. } else {
  46. $fields_code[] = " private {$type} \${$field};";
  47. }
  48. $methods_code[] = " public function set{$method_name}({$type} \${$field}): self " .
  49. "{ \$this->{$field} = \${$field}; return \$this; }" . "\n" .
  50. " public function get{$method_name}()" . ($type !== '' ? ": {$type} " : ' ') .
  51. "{ return \$this->{$field}; }" . "\n";
  52. }
  53. $fields_code = implode("\n", $fields_code);
  54. $methods_code = implode("\n", $methods_code) . "\n";
  55. $begin = '// {{{ Autocode';
  56. $end = '// }}} Autocode';
  57. $code = "
  58. {$begin}
  59. {$fields_code}
  60. {$methods_code}
  61. {$end}
  62. ";
  63. foreach (['/\\//' => '\\/', '/ /' => '\\ '] as $from => $to) {
  64. $begin = preg_replace($from, $to, $begin);
  65. $end = preg_replace($from, $to, $end);
  66. }
  67. $in_file = file_get_contents($file);
  68. $out_file = preg_replace("/\\s*{$begin}[^\\/]*{$end}/m", $code, $in_file);
  69. file_put_contents($file, $out_file);
  70. }