Author: Johannes M. Schmitt (schmittjoh@gmail.com)
Inheritance: extends AbstractPhpMember, use trait gossi\codegen\model\parts\AbstractTrait, use trait gossi\codegen\model\parts\FinalTrait, use trait gossi\codegen\model\parts\ParametersTrait, use trait gossi\codegen\model\parts\BodyTrait, use trait gossi\codegen\model\parts\ReferenceReturnTrait
 public function testMethods()
 {
     $class = new PhpClass();
     $this->assertTrue($class->getMethods()->isEmpty());
     $this->assertSame($class, $class->setMethod($method = new PhpMethod('foo')));
     $this->assertSame(['foo' => $method], $class->getMethods()->toArray());
     $this->assertTrue($class->hasMethod('foo'));
     $this->assertSame($method, $class->getMethod('foo'));
     $this->assertSame($class, $class->removeMethod($method));
     $this->assertEquals([], $class->getMethods()->toArray());
     $class->setMethod($orphaned = new PhpMethod('orphaned'));
     $this->assertSame($class, $orphaned->getParent());
     $this->assertTrue($class->hasMethod($orphaned));
     $this->assertSame($class, $class->setMethods([$method, $method2 = new PhpMethod('bar')]));
     $this->assertSame(['foo' => $method, 'bar' => $method2], $class->getMethods()->toArray());
     $this->assertEquals(['foo', 'bar'], $class->getMethodNames()->toArray());
     $this->assertNull($orphaned->getParent());
     $this->assertSame($method, $class->getMethod($method));
     $this->assertTrue($class->hasMethod($method));
     $this->assertSame($class, $class->removeMethod($method));
     $this->assertFalse($class->hasMethod($method));
     $this->assertFalse($class->getMethods()->isEmpty());
     $class->clearMethods();
     $this->assertTrue($class->getMethods()->isEmpty());
     try {
         $this->assertEmpty($class->getMethod('method-not-found'));
     } catch (\InvalidArgumentException $e) {
         $this->assertNotNull($e);
     }
 }
 public function testReferenceReturned()
 {
     $method = new PhpMethod('needsName');
     $this->assertFalse($method->isReferenceReturned());
     $this->assertSame($method, $method->setReferenceReturned(true));
     $this->assertTrue($method->isReferenceReturned());
     $this->assertSame($method, $method->setReferenceReturned(false));
     $this->assertFalse($method->isReferenceReturned());
 }
 /**
  * @param PhpMethod $a
  * @param PhpMethod $b
  */
 public function compare($a, $b)
 {
     if ($a->isStatic() !== ($isStatic = $b->isStatic())) {
         return $isStatic ? 1 : -1;
     }
     if (($aV = $a->getVisibility()) !== ($bV = $b->getVisibility())) {
         $aV = 'public' === $aV ? 3 : ('protected' === $aV ? 2 : 1);
         $bV = 'public' === $bV ? 3 : ('protected' === $bV ? 2 : 1);
         return $aV > $bV ? -1 : 1;
     }
     return strcasecmp($a->getName(), $b->getName());
 }
 public function testVisitMethodWithCallable()
 {
     if (PHP_VERSION_ID < 50400) {
         $this->markTestSkipped('`callable` is only supported in PHP >=5.4.0');
     }
     $method = new PhpMethod('foo');
     $parameter = new PhpParameter('bar');
     $parameter->setType('callable');
     $method->addParameter($parameter);
     $visitor = new DefaultVisitor();
     $visitor->visitMethod($method);
     $this->assertEquals($this->getContent('callable_parameter.php'), $visitor->getContent());
 }
 /**
  * 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());
 }
    public function testFromReflection()
    {
        $classDoc = new Docblock('/**
 * Doc Comment.
 *
 * @author Johannes M. Schmitt <*****@*****.**>
 */');
        $propDoc = new Docblock('/**
 * @var integer
 */');
        $class = new PhpClass();
        $class->setQualifiedName('gossi\\codegen\\tests\\fixture\\Entity')->setAbstract(true)->setDocblock($classDoc)->setDescription($classDoc->getShortDescription())->setLongDescription($classDoc->getLongDescription())->setProperty(PhpProperty::create('id')->setVisibility('private')->setDocblock($propDoc)->setType('integer')->setDescription($propDoc->getShortDescription()))->setProperty(PhpProperty::create('enabled')->setVisibility('private')->setDefaultValue(false));
        $methodDoc = new Docblock('/**
 * Another doc comment.
 *
 * @param unknown_type $a
 * @param array        $b
 * @param \\stdClass    $c
 * @param string       $d
 * @param callable     $e
 */');
        $method = PhpMethod::create('__construct')->setFinal(true)->addParameter(PhpParameter::create('a')->setType('unknown_type'))->addParameter(PhpParameter::create()->setName('b')->setType('array')->setPassedByReference(true))->addParameter(PhpParameter::create()->setName('c')->setType('\\stdClass'))->addParameter(PhpParameter::create()->setName('d')->setType('string')->setDefaultValue('foo'))->addParameter(PhpParameter::create()->setName('e')->setType('callable'))->setDocblock($methodDoc)->setDescription($methodDoc->getShortDescription())->setLongDescription($methodDoc->getLongDescription());
        $class->setMethod($method);
        $class->setMethod(PhpMethod::create('foo')->setAbstract(true)->setVisibility('protected'));
        $class->setMethod(PhpMethod::create('bar')->setStatic(true)->setVisibility('private'));
        $this->assertEquals($class, PhpClass::fromReflection(new \ReflectionClass('gossi\\codegen\\tests\\fixture\\Entity')));
        $class = new PhpClass('gossi\\codegen\\tests\\fixture\\ClassWithConstants');
        $class->setConstant('FOO', 'bar');
        $this->assertEquals($class, PhpClass::fromReflection(new \ReflectionClass('gossi\\codegen\\tests\\fixture\\ClassWithConstants')));
    }
 public function testReturnType()
 {
     $expected = "public function foo(): int {\n}\n";
     $generator = new ModelGenerator(['generateReturnTypeHints' => true, 'generateDocblock' => false]);
     $method = PhpMethod::create('foo')->setType('int');
     $this->assertEquals($expected, $generator->generate($method));
 }
 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);
 }
 public function testMethods()
 {
     $class = new PhpClass();
     $this->assertEquals(array(), $class->getMethods());
     $this->assertSame($class, $class->setMethod($method = new PhpMethod('foo')));
     $this->assertSame(array('foo' => $method), $class->getMethods());
     $this->assertTrue($class->hasMethod('foo'));
     $this->assertSame($method, $class->getMethod('foo'));
     $this->assertSame($class, $class->removeMethod($method));
     $this->assertEquals(array(), $class->getMethods());
     $class->setMethod($orphaned = new PhpMethod('orphaned'));
     $this->assertSame($class, $orphaned->getParent());
     $this->assertTrue($class->hasMethod($orphaned));
     $this->assertSame($class, $class->setMethods([$method, $method2 = new PhpMethod('bar')]));
     $this->assertSame(['foo' => $method, 'bar' => $method2], $class->getMethods());
     $this->assertNull($orphaned->getParent());
 }
 /**
  * @return PhpTrait
  */
 private function createDummyTrait()
 {
     $trait = new PhpTrait('DummyTrait');
     $trait->setNamespace('gossi\\codegen\\tests\\fixture');
     $trait->setDescription('Dummy docblock');
     $trait->setMethod(PhpMethod::create('foo')->setVisibility('public'));
     $trait->setProperty(PhpProperty::create('iAmHidden')->setVisibility('private'));
     $trait->addUseStatement('gossi\\codegen\\tests\\fixture\\VeryDummyTrait');
     $trait->addTrait('VeryDummyTrait');
     $trait->generateDocblock();
     return $trait;
 }
 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 testFromReflection()
 {
     $trait = new PhpTrait('DummyTrait');
     $trait->setNamespace('gossi\\codegen\\tests\\fixture');
     $trait->setDescription('Dummy docblock');
     $trait->setMethod(PhpMethod::create('foo')->setVisibility('public'));
     $trait->setProperty(PhpProperty::create('iAmHidden')->setVisibility('private'));
     // @TODO: this alias is only a workaround
     $trait->addUseStatement('gossi\\codegen\\tests\\fixture\\VeryDummyTrait');
     $trait->addTrait('VeryDummyTrait');
     $trait->generateDocblock();
     $this->assertEquals($trait, PhpTrait::fromReflection(new \ReflectionClass('gossi\\codegen\\tests\\fixture\\DummyTrait')));
 }
Example #13
0
 public function testDefaultMethodComparator()
 {
     $list = new ArrayList();
     $list->add(PhpMethod::create('moop')->setStatic(true));
     $list->add(PhpMethod::create('arr')->setVisibility(PhpMethod::VISIBILITY_PRIVATE));
     $list->add(PhpMethod::create('bar')->setVisibility(PhpMethod::VISIBILITY_PROTECTED));
     $list->add(PhpMethod::create('foo'));
     $list->add(PhpMethod::create('baz'));
     $list->sort(new DefaultMethodComparator());
     $ordered = $list->map(function ($item) {
         return $item->getName();
     })->toArray();
     $this->assertEquals(['moop', 'baz', 'foo', 'bar', 'arr'], $ordered);
 }
 /**
  * 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());
 }
 /**
  * Adds a method
  *
  * @param PhpMethod $method
  * @return $this
  */
 public function setMethod(PhpMethod $method)
 {
     $method->setParent($this);
     $this->methods->set($method->getName(), $method);
     return $this;
 }
 public function visitMethod(ClassMethod $node)
 {
     $m = new PhpMethod($node->name);
     $m->setAbstract($node->isAbstract());
     $m->setFinal($node->isFinal());
     $m->setVisibility($this->getVisibility($node));
     $m->setStatic($node->isStatic());
     $m->setReferenceReturned($node->returnsByRef());
     // docblock
     if (($doc = $node->getDocComment()) !== null) {
         $m->setDocblock($doc->getReformattedText());
         $docblock = $m->getDocblock();
         $m->setDescription($docblock->getShortDescription());
         $m->setLongDescription($docblock->getLongDescription());
     }
     // params
     $params = $m->getDocblock()->getTags('param');
     foreach ($node->params as $param) {
         /* @var $param Param */
         $p = new PhpParameter();
         $p->setName($param->name);
         $p->setPassedByReference($param->byRef);
         if (is_string($param->type)) {
             $p->setType($param->type);
         } else {
             if ($param->type instanceof Name) {
                 $p->setType(implode('\\', $param->type->parts));
             }
         }
         $this->parseValue($p, $param);
         $tag = $params->find($p, function (ParamTag $t, $p) {
             return $t->getVariable() == '$' . $p->getName();
         });
         if ($tag !== null) {
             $p->setType($tag->getType(), $tag->getDescription());
         }
         $m->addParameter($p);
     }
     // return type and description
     $returns = $m->getDocblock()->getTags('return');
     if ($returns->size() > 0) {
         $return = $returns->get(0);
         $m->setType($return->getType(), $return->getDescription());
     }
     // body
     $stmts = $node->getStmts();
     if (is_array($stmts) && count($stmts)) {
         $prettyPrinter = new PrettyPrinter();
         $m->setBody($prettyPrinter->prettyPrint($stmts));
     }
     $this->struct->setMethod($m);
 }
 private function createDummyInterface()
 {
     $interface = PhpInterface::create('DummyInterface')->setNamespace('gossi\\codegen\\tests\\fixture')->setDescription('Dummy docblock')->setMethod(PhpMethod::create('foo'));
     $interface->generateDocblock();
     return $interface;
 }
Example #18
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}");
 }
Example #19
0
 public function testEmptyMethod()
 {
     $method = new PhpMethod(self::METHOD);
     $method->generateDocblock();
     $this->assertTrue($method->getDocblock()->isEmpty());
 }
 public function testFromReflection()
 {
     $interface = PhpInterface::create('DummyInterface')->setNamespace('gossi\\codegen\\tests\\fixture')->setDescription('Dummy docblock')->setMethod(PhpMethod::create('foo'));
     $interface->generateDocblock();
     $this->assertEquals($interface, PhpInterface::fromReflection(new \ReflectionClass('gossi\\codegen\\tests\\fixture\\DummyInterface')));
 }
 public function visitMethod(PhpMethod $method)
 {
     $this->visitDocblock($method->getDocblock());
     if ($method->isAbstract()) {
         $this->writer->write('abstract ');
     }
     $this->writer->write($method->getVisibility() . ' ');
     if ($method->isStatic()) {
         $this->writer->write('static ');
     }
     $this->writer->write('function ');
     if ($method->isReferenceReturned()) {
         $this->writer->write('& ');
     }
     $this->writer->write($method->getName() . '(');
     $this->writeParameters($method->getParameters());
     $this->writer->write(")");
     $this->writeFunctionReturnType($method->getType());
     if ($method->isAbstract() || $method->getParent() instanceof PhpInterface) {
         $this->writer->write(";\n\n");
         return;
     }
     $this->writer->writeln(' {')->indent()->writeln(trim($method->getBody()))->outdent()->rtrim()->write("}\n\n");
 }
 /**
  *
  * @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;
 }
Example #23
0
 $classDescription = $tableDescriptor->describe($targetNamespace . "Table");
 $class = new gossi\codegen\model\PhpClass($classDescription['identifier']);
 $class->setFinal(true);
 $escapedClassName = str_replace("\\", "\\\\", $class->getQualifiedName());
 $class->setProperty(PhpProperty::create("connection")->setType('\\PDO'));
 $constructor = PhpMethod::create("__construct");
 $constructor->addSimpleParameter("connection", '\\PDO');
 $constructor->setBody('$this->connection = $connection;');
 $class->setMethod($constructor);
 foreach ($classDescription['properties'] as $propertyIdentifier => $value) {
     $class->setProperty(PhpProperty::create($propertyIdentifier));
 }
 $querybuilder = $conn->createQueryBuilder();
 $foreignKeys = $table->getForeignKeys();
 foreach ($classDescription['methods'] as $methodIdentifier => $method) {
     $foreignKeyMethod = PhpMethod::create($methodIdentifier);
     $foreignKeyMapParameters = [];
     $foreignKeyMethod->setParameters(array_map(function ($methodParameter) {
         return PhpParameter::create($methodParameter);
     }, $method['parameters']));
     $query = $querybuilder->select($method['query'][1]['fields'])->from($method['query'][1]['from']);
     if (strlen($method['query'][1]['where']) > 0) {
         $query->where($method['query'][1]['where']);
     }
     $foreignKeyMethod->setBody('$statement = $this->connection->prepare("' . $query . '", \\PDO::FETCH_CLASS, "' . str_replace("\\", "\\\\", $escapedClassName) . '", [$connection]);' . PHP_EOL . join(PHP_EOL, array_map(function ($methodParameter) {
         return '$statement->bindParam(":' . $methodParameter . '", $' . $methodParameter . ', \\PDO::PARAM_STR);';
     }, $method['parameters'])) . PHP_EOL . 'return $statement->fetchAll();');
     $class->setMethod($foreignKeyMethod);
 }
 $generator = new CodeGenerator();
 file_put_contents($tablesDirectory . DIRECTORY_SEPARATOR . $tableName . '.php', '<?php' . PHP_EOL . $generator->generate($class));
 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);
 }
Example #25
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}");
 }