Generates code for a model and puts it into a file with statements. Can also generate header comments.
Author: Thomas Gossmann
Inheritance: extends CodeGenerator
 public function testConfig()
 {
     $generator = new CodeFileGenerator(null);
     $this->assertTrue($generator->getConfig() instanceof CodeFileGeneratorConfig);
     $config = new CodeFileGeneratorConfig();
     $generator = new CodeFileGenerator($config);
     $this->assertSame($config, $generator->getConfig());
 }
 public function sample()
 {
     $class = new PhpClass('Sample');
     $class->setNamespace('name\\space');
     $class->setProperty(PhpProperty::create('string')->setType('string', 'String'));
     $writer = new Writer();
     $class->setMethod(PhpMethod::create('get')->setDescription(['Return string'])->setType('string')->setBody($writer->writeln('return $this->string;')->getContent()));
     $writer = new Writer();
     $class->setMethod(PhpMethod::create('set')->setDescription(['Set string'])->addSimpleDescParameter('string', 'string', 'String')->setType('$this')->setBody($writer->writeln('$this->string = $string;')->writeln('return $this;')->getContent()));
     $generator = new CodeFileGenerator();
     $code = $generator->generate($class);
     file_put_contents('tmp/origin/Gossi.php', (string) $code);
 }
 public function testUseStatements()
 {
     $class = new PhpClass('Foo\\Bar');
     $class->addUseStatement('Bam\\Baz');
     $codegen = new CodeFileGenerator(['generateDocblock' => false, 'generateEmptyDocblock' => false]);
     $code = $codegen->generate($class);
     $this->assertEquals($this->getGeneratedContent('FooBar.php'), $code);
     $class = new PhpClass('Foo\\Bar');
     $class->addUseStatement('Bam\\Baz', 'BamBaz');
     $codegen = new CodeFileGenerator(['generateDocblock' => false, 'generateEmptyDocblock' => false]);
     $code = $codegen->generate($class);
     $this->assertEquals($this->getGeneratedContent('FooBarWithAlias.php'), $code);
     $class = new PhpClass('Foo');
     $class->addUseStatement('Bar');
     $generator = new ModelGenerator();
     $code = $generator->generate($class);
     $expected = 'class Foo {' . "\n" . '}';
     $this->assertEquals($expected, $code);
 }
Beispiel #4
0
 /**
  * Construction du fichier d'helper pour l'ide afin d'avoir l'autocompletion
  *
  */
 public static function build()
 {
     $file = storage_path('/../bootstrap/') . static::CLASS_NAME . '.php';
     // recuperation des données
     $constant = \query('reference', ['reference_id'])->whereNull('deleted_at')->pluck('reference_id');
     $constant = array_combine($constant, $constant);
     // generate class
     $class = new PhpClass();
     $class->setQualifiedName(static::CLASS_NAME);
     $class->setConstants($constant);
     // generate code
     $generator = new CodeFileGenerator();
     $content = $generator->generate($class);
     file_put_contents($file, $content);
 }
 public function testFromFileWithComments()
 {
     $class = PhpClass::fromFile(__DIR__ . '/../fixture/ClassWithComments.php');
     $this->assertClassWithComments($class);
     $generator = new CodeFileGenerator();
     $code = $generator->generate($class);
     $this->assertEquals(file_get_contents(__DIR__ . '/../fixture/ClassWithComments.php'), $code);
 }
Beispiel #6
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $table = prompt("Table to create model for");
     $this->description["description"] = prompt("Description");
     if (!$table) {
         $output->writeln("Error, table name is not supplied.");
         exit;
     }
     // Setup the path and make sure it doesn't already exist
     $path = __DIR__ . "/../Model/Database/{$table}.php";
     if (file_exists($path)) {
         return $output->writeln("Error, file already exists");
     }
     // Load app
     $app = \ProjectRena\RenaApp::getInstance();
     // Load the table, if it exists in the first place
     $tableColums = $app->Db->query("SHOW COLUMNS FROM {$table}");
     // Generate the start of the model code
     $class = new PhpClass();
     $class->setQualifiedName("ProjectRena\\Model\\Database\\{$table}")->setProperty(PhpProperty::create("app")->setVisibility("private")->setDescription("The Slim Application"))->setProperty(PhpProperty::create("db")->setVisibility("private")->setDescription("The database connection"))->setMethod(PhpMethod::create("__construct")->addParameter(PhpParameter::create("app")->setType("RenaApp"))->setBody("\$this->app = \$app;\n\r\n                \$this->db = \$app->Db;\n"))->setDescription($this->description)->declareUse("ProjectRena\\RenaApp");
     $nameFields = array();
     $idFields = array();
     foreach ($tableColums as $get) {
         // This is for the getByName selector(s)
         if (stristr($get["Field"], "name")) {
             $nameFields[] = $get["Field"];
         }
         // This is for the getByID selector(s)
         if (strstr($get["Field"], "ID")) {
             $idFields[] = $get["Field"];
         }
     }
     // Get generator
     foreach ($nameFields as $name) {
         // get * by Name
         $class->setMethod(PhpMethod::create("getAllBy" . ucfirst($name))->addParameter(PhpParameter::create($name))->setVisibility("public")->setBody("return \$this->db->query(\"SELECT * FROM {$table} WHERE {$name} = :{$name}\", array(\":{$name}\" => \${$name}));"));
     }
     foreach ($idFields as $id) {
         // get * by ID,
         $class->setMethod(PhpMethod::create("getAllBy" . ucfirst($id))->addParameter(PhpParameter::create($id)->setType("int"))->setVisibility("public")->setBody("return \$this->db->query(\"SELECT * FROM {$table} WHERE {$id} = :{$id}\", array(\":{$id}\" => \${$id}));"));
     }
     foreach ($nameFields as $name) {
         foreach ($tableColums as $get) {
             // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID
             if ($get["Field"] == $name) {
                 continue;
             }
             // Skip the id field
             if ($get["Field"] == "id") {
                 continue;
             }
             $class->setMethod(PhpMethod::create("get" . ucfirst($get["Field"]) . "By" . ucfirst($name))->addParameter(PhpParameter::create($name))->setVisibility("public")->setBody("return \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$name} = :{$name}\", \"{$get["Field"]}\", array(\":{$name}\" => \${$name}));"));
         }
     }
     foreach ($idFields as $id) {
         foreach ($tableColums as $get) {
             // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID
             if ($get["Field"] == $id) {
                 continue;
             }
             // Skip the id field
             if ($get["Field"] == "id") {
                 continue;
             }
             $class->setMethod(PhpMethod::create("get" . ucfirst($get["Field"]) . "By" . ucfirst($id))->addParameter(PhpParameter::create($id))->setVisibility("public")->setBody("return \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$id} = :{$id}\", \"{$get["Field"]}\", array(\":{$id}\" => \${$id}));"));
         }
     }
     // Update generator
     foreach ($nameFields as $name) {
         foreach ($tableColums as $get) {
             // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID
             if ($get["Field"] == $name) {
                 continue;
             }
             // Skip the id field
             if ($get["Field"] == "id") {
                 continue;
             }
             $class->setMethod(PhpMethod::create("update" . ucfirst($get["Field"]) . "By" . ucfirst($name))->addParameter(PhpParameter::create($get["Field"]))->addParameter(PhpParameter::create($name))->setVisibility("public")->setBody("\$exists = \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$name} = :{$name}\", \"{$get["Field"]}\", array(\":{$name}\" => \${$name}));\r\n                     if(!empty(\$exists)){\r\n                        \$this->db->execute(\"UPDATE {$table} SET {$get["Field"]} = :{$get["Field"]} WHERE {$name} = :{$name}\", array(\":{$name}\" => \${$name}, \":{$get["Field"]}\" => \${$get["Field"]}));}\r\n                    "));
         }
     }
     foreach ($idFields as $id) {
         foreach ($tableColums as $get) {
             // If the fields match, skip it.. no reason to get/set allianceID where allianceID = allianceID
             if ($get["Field"] == $id) {
                 continue;
             }
             // Skip the id field
             if ($get["Field"] == "id") {
                 continue;
             }
             $class->setMethod(PhpMethod::create("update" . ucfirst($get["Field"]) . "By" . ucfirst($id))->addParameter(PhpParameter::create($get["Field"]))->addParameter(PhpParameter::create($id))->setVisibility("public")->setBody("\$exists = \$this->db->queryField(\"SELECT {$get["Field"]} FROM {$table} WHERE {$id} = :{$id}\", \"{$get["Field"]}\", array(\":{$id}\" => \${$id}));\r\n                     if(!empty(\$exists))\r\n                     {\r\n                        \$this->db->execute(\"UPDATE {$table} SET {$get["Field"]} = :{$get["Field"]} WHERE {$id} = :{$id}\", array(\":{$id}\" => \${$id}, \":{$get["Field"]}\" => \${$get["Field"]}));}\r\n                    "));
         }
     }
     // Global insert generator (Yes it's ugly as shit..)
     $inserter = "public function insertInto" . ucfirst($table) . "(";
     foreach ($tableColums as $field) {
         // Skip the ID field
         if ($field["Field"] == "id") {
             continue;
         }
         $inserter .= "\${$field["Field"]}, ";
     }
     $inserter = rtrim(trim($inserter), ",") . ")";
     $inserter .= "{";
     $inserter .= "\$this->db->execute(\"INSERT INTO {$table} (";
     foreach ($tableColums as $field) {
         if ($field["Field"] == "id") {
             continue;
         }
         $inserter .= $field["Field"] . ", ";
     }
     $inserter = rtrim(trim($inserter), ",") . ") ";
     $inserter .= "VALUES (";
     foreach ($tableColums as $field) {
         if ($field["Field"] == "id") {
             continue;
         }
         $inserter .= ":" . $field["Field"] . ", ";
     }
     $inserter = rtrim(trim($inserter), ",") . ")\", ";
     $inserter .= "array(";
     foreach ($tableColums as $field) {
         if ($field["Field"] == "id") {
             continue;
         }
         $inserter .= "\":" . $field["Field"] . "\" => \${$field["Field"]}, ";
     }
     $inserter = rtrim(trim($inserter), ",") . "));";
     $inserter .= "}}";
     $generator = new CodeFileGenerator();
     $code = $generator->generate($class);
     $code = rtrim(trim($code), "}");
     $code .= $inserter;
     $formatter = new Formatter();
     $code = $formatter->format($code);
     file_put_contents($path, $code);
     chmod($path, 0777);
     $output->writeln("Model created: {$path}");
 }
 public function testStrictTypesDeclaration()
 {
     $expected = "<?php\ndeclare(strict_types=1);\n\nfunction fn(\$a) {\n}\n";
     $fn = PhpFunction::create('fn')->addParameter(PhpParameter::create('a'));
     $codegen = new CodeFileGenerator(['generateDocblock' => false, 'generateEmptyDocblock' => false, 'declareStrictTypes' => true]);
     $code = $codegen->generate($fn);
     $this->assertEquals($expected, $code);
 }
 /**
  * @param $name
  * @param OutputInterface $output
  *
  * @return mixed
  */
 private function resque($name, $output)
 {
     $path = __DIR__ . "/../Task/Resque/{$name}.php";
     if (file_exists($path)) {
         return $output->writeln("Error, file already exists");
     }
     $class = new PhpClass();
     $class->setQualifiedName("Mira\\Task\\Resque\\{$name}")->setProperty(PhpProperty::create("app")->setVisibility("private")->setDescription("The Slim Application"))->setDescription($this->descr)->setMethod(PhpMethod::create("setUp")->setVisibility("public")->setDescription("Sets up the task (Setup \$this->crap and such here)")->setBody("\$this->app = \\Mira\\MiraApp::getInstance();"))->setMethod(PhpMethod::create("perform")->setVisibility("public")->setDescription("Performs the task, can access all \$this->crap setup in setUp)"))->setMethod(PhpMethod::create("tearDown")->setVisibility("public")->setDescription("Tears the task down, unset \$this->crap and such")->setBody("\$this->app = null;"));
     $generator = new CodeFileGenerator();
     $code = $generator->generate($class);
     $formatter = new Formatter();
     $code = $formatter->format($code);
     file_put_contents($path, $code);
     $output->writeln("Resque Queue created: {$path}");
 }