Author: Thomas Gossmann
Inheritance: extends AbstractPhpStruct, implements gossi\codegen\model\GenerateableInterface, implements gossi\codegen\model\TraitsInterface, implements gossi\codegen\model\ConstantsInterface, implements gossi\codegen\model\PropertiesInterface, use trait gossi\codegen\model\parts\AbstractPart, use trait gossi\codegen\model\parts\ConstantsPart, use trait gossi\codegen\model\parts\FinalPart, use trait gossi\codegen\model\parts\InterfacesPart, use trait gossi\codegen\model\parts\PropertiesPart, use trait gossi\codegen\model\parts\TraitsPart
コード例 #1
0
 public function testExpression()
 {
     $class = new PhpClass('ClassWithExpression');
     $class->setConstant(PhpConstant::create('FOO', 'BAR'))->setProperty(PhpProperty::create('bembel')->setExpression("['ebbelwoi' => 'is eh besser', 'als wie' => 'bier']"))->setMethod(PhpMethod::create('getValue')->addParameter(PhpParameter::create('arr')->setExpression('[self::FOO => \'baz\']')));
     $codegen = new CodeFileGenerator(['generateDocblock' => false]);
     $code = $codegen->generate($class);
     $this->assertEquals($this->getGeneratedContent('ClassWithExpression.php'), $code);
 }
コード例 #2
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // recuperation du controller
     $controller = $this->argument('controller');
     // création de la méthode
     $method = camel_case($this->argument('name'));
     $method = PhpMethod::create($method);
     $method->setStatic(true);
     // Gestion du body
     $body = file_get_contents(__DIR__ . '/stubs/table.stub');
     $method->setBody($body);
     // block de commentaire
     $dockblock = new Docblock();
     $dockblock->appendTag(TagFactory::create('name', 'Artisan'));
     $dockblock->appendTag(TagFactory::create('see', 'php artisan ffmake:table'));
     $dockblock->appendTag(TagFactory::create('generated', Carbon::now()));
     $method->setDocblock($dockblock);
     // Récupération du controller à mettre à jour
     $controller = ucfirst(camel_case($controller . '_controller'));
     $controller = new \ReflectionClass('App\\Http\\Controllers\\' . $controller);
     $class = PhpClass::fromReflection($controller)->setMethod($method);
     $class->setParentClassName('Controller');
     // fix la gestion des namespaec pour la parent class
     // Génration du code
     $generator = new CodeGenerator();
     $class = '<?php ' . $generator->generate($class);
     // inscription du code dans la classe
     file_put_contents($controller->getFileName(), $class);
     $this->info('Action generated dans le fichier : ' . $controller->getFileName());
 }
コード例 #3
0
 private function assertClassWithComments(PhpClass $class)
 {
     $docblock = $class->getDocblock();
     $this->assertEquals($docblock->getShortDescription(), $class->getDescription());
     $this->assertEquals($docblock->getLongDescription(), $class->getLongDescription());
     $this->assertEquals('A class with comments', $docblock->getShortDescription());
     $this->assertEquals('Here is a super dooper long-description', $docblock->getLongDescription());
     $this->assertTrue($docblock->getTags('author')->size() > 0);
     $this->assertTrue($docblock->getTags('since')->size() > 0);
     $FOO = $class->getConstant('FOO');
     $this->assertEquals('Best const ever', $FOO->getDescription());
     $this->assertEquals('Aaaand we go along long', $FOO->getLongDescription());
     $this->assertEquals('baz', $FOO->getTypeDescription());
     $this->assertEquals('string', $FOO->getType());
     $this->assertEquals('bar', $FOO->getValue());
     $propper = $class->getProperty('propper');
     $this->assertEquals('Best prop ever', $propper->getDescription());
     $this->assertEquals('Aaaand we go along long long', $propper->getLongDescription());
     $this->assertEquals('Wer macht sauber?', $propper->getTypeDescription());
     $this->assertEquals('string', $propper->getType());
     $this->assertEquals('Meister', $propper->getValue());
     $setup = $class->getMethod('setup');
     $this->assertEquals('Short desc', $setup->getDescription());
     $this->assertEquals('Looong desc', $setup->getLongDescription());
     $this->assertEquals('true on success and false if it fails', $setup->getTypeDescription());
     $this->assertEquals('boolean', $setup->getType());
     $moo = $setup->getParameter('moo');
     $this->assertEquals('makes a cow', $moo->getTypeDescription());
     $this->assertEquals('boolean', $moo->getType());
     $foo = $setup->getParameter('foo');
     $this->assertEquals('makes a fow', $foo->getTypeDescription());
     $this->assertEquals('string', $foo->getType());
 }
コード例 #4
0
ファイル: Fixtures.php プロジェクト: gossi/php-code-generator
 /**
  * Creates ClassWithComments
  * 
  * @return PhpClass
  */
 public static function createClassWithComments()
 {
     $class = PhpClass::create('gossi\\codegen\\tests\\fixtures\\ClassWithComments');
     $class->setDescription('A class with comments');
     $class->setLongDescription('Here is a super dooper long-description');
     $docblock = $class->getDocblock();
     $docblock->appendTag(AuthorTag::create('gossi'));
     $docblock->appendTag(SinceTag::create('0.2'));
     $class->setConstant(PhpConstant::create('FOO', 'bar')->setDescription('Best const ever')->setLongDescription('Aaaand we go along long')->setType('string')->setTypeDescription('baz'));
     $class->setProperty(PhpProperty::create('propper')->setDescription('best prop ever')->setLongDescription('Aaaand we go along long long')->setType('string')->setTypeDescription('Wer macht sauber?'));
     $class->setMethod(PhpMethod::create('setup')->setDescription('Short desc')->setLongDescription('Looong desc')->addParameter(PhpParameter::create('moo')->setType('boolean')->setTypeDescription('makes a cow'))->addParameter(PhpParameter::create('foo')->setType('foo', 'makes a fow'))->setType('boolean', 'true on success and false if it fails'));
     return $class;
 }
コード例 #5
0
 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);
 }
コード例 #6
0
 private function buildSignature(PhpClass $model)
 {
     if ($model->isAbstract()) {
         $this->writer->write('abstract ');
     }
     if ($model->isFinal()) {
         $this->writer->write('final ');
     }
     $this->writer->write('class ');
     $this->writer->write($model->getName());
     if ($parentClassName = $model->getParentClassName()) {
         $this->writer->write(' extends ' . $parentClassName);
     }
     if ($model->hasInterfaces()) {
         $this->writer->write(' implements ');
         $this->writer->write(implode(', ', $model->getInterfaces()->toArray()));
     }
 }
コード例 #7
0
ファイル: ModelTask.php プロジェクト: milleruk/projectRena
 /**
  * @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}");
 }
コード例 #8
0
 public function testDescripion()
 {
     $class = new PhpClass();
     $class->setDescription(['multiline', 'description']);
     $this->assertEquals("multiline\ndescription", $class->getDescription());
 }
コード例 #9
0
 /**
  * @expectedException \InvalidArgumentException
  */
 public function testNonExistentGetAttribute()
 {
     $class = new PhpClass();
     $class->getAttribute('nope');
 }
コード例 #10
0
ファイル: Reference.php プロジェクト: frenchfrogs/reference
 /**
  * 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);
 }
コード例 #11
0
 public function testRequiredFiles()
 {
     $class = new PhpClass();
     $this->assertEquals(array(), $class->getRequiredFiles());
     $this->assertSame($class, $class->setRequiredFiles(array('foo')));
     $this->assertEquals(array('foo'), $class->getRequiredFiles());
     $this->assertSame($class, $class->addRequiredFile('bar'));
     $this->assertEquals(array('foo', 'bar'), $class->getRequiredFiles());
 }
コード例 #12
0
 /**
  * @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}");
 }
コード例 #13
0
 /**
  *
  * @return PhpClass
  */
 private function getClass()
 {
     $class = PhpClass::create()->setName('GenerationTestClass')->setMethod(PhpMethod::create('a'))->setMethod(PhpMethod::create('b'))->setProperty(PhpProperty::create('a'))->setProperty(PhpProperty::create('b'))->setConstant('a', 'foo')->setConstant('b', 'bar');
     return $class;
 }
コード例 #14
0
 public function testFromReflection()
 {
     $class = Fixtures::createEntity();
     $this->assertEquals($class, PhpClass::fromReflection(new \ReflectionClass('gossi\\codegen\\tests\\fixtures\\Entity')));
 }
コード例 #15
0
 protected function assertValueClass(PhpClass $class)
 {
     $values = $class->getMethod('values');
     $this->isValueString($values->getParameter('paramString'));
     $this->isValueInteger($values->getParameter('paramInteger'));
     $this->isValueFloat($values->getParameter('paramFloat'));
     $this->isValueBool($values->getParameter('paramBool'));
     $this->isValueNull($values->getParameter('paramNull'));
 }
コード例 #16
0
 public function testRequireTraitsClass()
 {
     $class = PhpClass::create('RequireTraitsClass')->addRequiredFile('FooBar.php')->addRequiredFile('ABClass.php')->addTrait('Iterator');
     $generator = new ModelGenerator();
     $code = $generator->generate($class);
     $this->assertEquals($this->getGeneratedContent('RequireTraitsClass.php'), $code);
 }
コード例 #17
0
 public function testMethodReturnTypeHinting()
 {
     $class = PhpClass::create()->setName('GenerationTestClass')->setMethod(PhpMethod::create('a')->addParameter(PhpParameter::create('b'))->setType('int'));
     $expected = "class GenerationTestClass {\n\n\tpublic function a(\$b): int {\n\t}\n}";
     $codegen = new CodeGenerator(['generateDocblock' => false, 'generateEmptyDocblock' => false, 'generateReturnTypeHints' => true]);
     $code = $codegen->generate($class);
     $this->assertEquals($expected, $code);
 }
コード例 #18
0
 public function testEmptyClass()
 {
     $class = new PhpClass();
     $class->generateDocblock();
     $this->assertTrue($class->getDocblock()->isEmpty());
 }
コード例 #19
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $controller = $this->argument('controller');
     // création de la méthode
     $method = camel_case($this->argument('method') . '_' . $this->argument('name'));
     $method = PhpMethod::create($method);
     // PARAMS
     $this->generateParams($method);
     // BODY
     $body = '';
     $body .= $this->generateAcl();
     // TEMPLATE
     $template = camel_case('template_' . $this->option('template'));
     if (!method_exists($this, $template)) {
         exc('Impossible de trouver le template : ' . $template);
     }
     $body .= call_user_func([$this, $template]);
     $method->setBody($body);
     // DOCKBOCK
     $dockblock = new Docblock();
     $dockblock->appendTag(TagFactory::create('name', 'Artisan'));
     $dockblock->appendTag(TagFactory::create('see', 'php artisan ffmake:action'));
     $dockblock->appendTag(TagFactory::create('generated', Carbon::now()));
     $method->setDocblock($dockblock);
     // CONTROLLER
     $controller = ucfirst(camel_case($controller . '_controller'));
     $controller = new \ReflectionClass('App\\Http\\Controllers\\' . $controller);
     $class = PhpClass::fromReflection($controller)->setMethod($method);
     $class->setParentClassName('Controller');
     // fix la gestion des namespaec pour la parent class
     // GENERATION
     $generator = new CodeGenerator();
     $class = '<?php ' . $generator->generate($class);
     // inscription du code dans la classe
     file_put_contents($controller->getFileName(), $class);
     $this->info('Action generated dans le fichier : ' . $controller->getFileName());
 }