Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class ModelGenerator {
- private $tableName;
- private $columns;
- public function __construct($tableName, $columns) {
- $this->tableName = $tableName;
- $this->columns = $columns;
- }
- private function convertToPascalCase($str) {
- return str_replace(' ', '', ucwords(str_replace('_', ' ', $str)));
- }
- private function convertToCamelCase($str) {
- $str = $this->convertToPascalCase($str);
- return lcfirst($str);
- }
- public function generateModel() {
- $modelName = $this->convertToPascalCase($this->tableName);
- $code = "<?php\n\n";
- $code .= "/**\n";
- $code .= " * This file was automatically generated by ModelGenerator.\n";
- $code .= " * Generated on: " . date('Y-m-d H:i:s') . "\n";
- $code .= " */\n\n";
- $code .= "class $modelName\n";
- $code .= "{\n";
- foreach ($this->columns as $columnName => $columnType) {
- $propertyName = $this->convertToCamelCase($columnName);
- $code .= "\tprivate $$propertyName;\n\n";
- $code .= "\tpublic function get" . ucfirst($propertyName) . "()\n";
- $code .= "\t{\n";
- $code .= "\t\treturn \$this->$propertyName;\n";
- $code .= "\t}\n\n";
- $code .= "\tpublic function set" . ucfirst($propertyName) . "(\$value)\n";
- $code .= "\t{\n";
- $code .= "\t\t\$this->$propertyName = \$value;\n";
- $code .= "\t}\n\n";
- }
- $code .= "}\n";
- return $code;
- }
- }
- // Read the JSON file path from command-line arguments
- if (count($argv) < 2) {
- echo "Usage: php ModelGenerator.php <json_file_path>" . PHP_EOL;
- exit(1);
- }
- $jsonFilePath = $argv[1];
- if (!file_exists($jsonFilePath)) {
- echo "Error: JSON file not found: $jsonFilePath" . PHP_EOL;
- exit(1);
- }
- // Read the JSON file
- $jsonData = file_get_contents($jsonFilePath);
- $tableData = json_decode($jsonData, true);
- if ($tableData === null) {
- echo "Error: Invalid JSON format" . PHP_EOL;
- exit(1);
- }
- // Extract table name and columns from JSON data
- $tableName = key($tableData);
- $columns = $tableData[$tableName];
- // Create an instance of ModelGenerator
- $modelGenerator = new ModelGenerator($tableName, $columns);
- // Generate the model code
- $modelCode = $modelGenerator->generateModel();
- // Get the directory of the JSON file
- $jsonFileDir = dirname($jsonFilePath);
- // Specify the output file path
- $outputFilePath = $jsonFileDir . '/' . ucfirst($tableName) . '.php';
- // Output the generated code to a file
- if (file_put_contents($outputFilePath, $modelCode) === false) {
- echo "Error: Failed to write the output file: $outputFilePath" . PHP_EOL;
- exit(1);
- }
- echo "Model class generated successfully: $outputFilePath" . PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment