Author: Johannes M. Schmitt (schmittjoh@gmail.com)
Inheritance: extends AbstractModel, use trait gossi\codegen\model\parts\NameTrait, use trait gossi\codegen\model\parts\DefaultValueTrait, use trait gossi\codegen\model\parts\TypeTrait
 public function testType()
 {
     $param = new PhpParameter();
     $this->assertNull($param->getType());
     $this->assertSame($param, $param->setType('array'));
     $this->assertEquals('array', $param->getType());
     $this->assertSame($param, $param->setType('array', 'boo!'));
     $this->assertEquals('boo!', $param->getTypeDescription());
 }
 /**
  * A quick way to add a parameter with description which is created from the given parameters
  * 
  * @param string      $name
  * @param null|string $type
  * @param null|string $typeDescription
  * @param mixed       $defaultValue omit the argument to define no default value
  *
  * @return $this
  */
 public function addSimpleDescParameter($name, $type = null, $typeDescription = null, $defaultValue = null)
 {
     $parameter = new PhpParameter($name);
     $parameter->setType($type);
     $parameter->setTypeDescription($typeDescription);
     if (3 < func_num_args() == 3) {
         $parameter->setDefaultValue($defaultValue);
     }
     $this->addParameter($parameter);
     return $this;
 }
 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());
 }
    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')));
    }
Esempio n. 5
0
 public function testValues()
 {
     $this->isValueString(PhpParameter::create()->setValue('hello'));
     $this->isValueInteger(PhpParameter::create()->setValue(2));
     $this->isValueFloat(PhpParameter::create()->setValue(0.2));
     $this->isValueBool(PhpParameter::create()->setValue(false));
     $this->isValueNull(PhpParameter::create()->setValue(null));
 }
 public function testParameters()
 {
     $generator = new ModelGenerator();
     $method = PhpMethod::create('foo')->addParameter(PhpParameter::create('bar'));
     $this->assertEquals("public function foo(\$bar) {\n}\n", $generator->generate($method));
     $method = PhpMethod::create('foo')->addParameter(PhpParameter::create('bar'))->addParameter(PhpParameter::create('baz'));
     $this->assertEquals("public function foo(\$bar, \$baz) {\n}\n", $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);
 }
 private function paramE(\ReflectionParameter $param)
 {
     $param = PhpParameter::fromReflection($param);
     $this->assertEquals('e', $param->getName());
     $this->assertFalse($param->isPassedByReference());
     $this->assertEmpty($param->getValue());
     $this->assertEquals('callable', $param->getType());
 }
    public function testFromReflection()
    {
        $doc = new Docblock('/**
 * Makes foo with bar
 * 
 * @param string $baz
 * @return string
 */');
        $function = new PhpFunction('wurst');
        $function->addParameter(PhpParameter::create('baz')->setDefaultValue(null)->setType('string'))->setBody('return \'wurst\';')->setDocblock($doc)->setDescription($doc->getShortDescription())->setLongDescription($doc->getLongDescription());
        $this->assertEquals($function, PhpFunction::fromReflection(new \ReflectionFunction('wurst')));
    }
Esempio n. 10
0
 public static function fromReflection(\ReflectionFunction $ref)
 {
     $function = PhpFunction::create($ref->name)->setReferenceReturned($ref->returnsReference())->setBody(ReflectionUtils::getFunctionBody($ref));
     $docblock = new Docblock($ref);
     $function->setDocblock($docblock);
     $function->setDescription($docblock->getShortDescription());
     $function->setLongDescription($docblock->getLongDescription());
     foreach ($ref->getParameters() as $refParam) {
         assert($refParam instanceof \ReflectionParameter);
         // hmm - assert here?
         $param = PhpParameter::fromReflection($refParam);
         $function->addParameter($param);
     }
     return $function;
 }
 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);
 }
 /**
  * Génération des paramètres de la méthode
  *
  * @param PhpMethod $method
  * @return $this
  */
 protected function generateParams(PhpMethod $method)
 {
     // PARAMS
     foreach ($this->getParams() as $name => $info) {
         $param = PhpParameter::create($name);
         if (isset($info['type'])) {
             $param->setType($info['type']);
         }
         if (isset($info['value'])) {
             // Cas de la valeur non obligatoire
             if ($info['value'] == 'null') {
                 $info['value'] = null;
             }
             $param->setValue($info['value']);
         }
         $method->addParameter($param);
     }
     return $this;
 }
 public function testValues()
 {
     $generator = new ModelGenerator();
     $prop = PhpParameter::create('foo')->setValue('string');
     $this->assertEquals('$foo = \'string\'', $generator->generate($prop));
     $prop = PhpParameter::create('foo')->setValue(300);
     $this->assertEquals('$foo = 300', $generator->generate($prop));
     $prop = PhpParameter::create('foo')->setValue(162.5);
     $this->assertEquals('$foo = 162.5', $generator->generate($prop));
     $prop = PhpParameter::create('foo')->setValue(true);
     $this->assertEquals('$foo = true', $generator->generate($prop));
     $prop = PhpParameter::create('foo')->setValue(false);
     $this->assertEquals('$foo = false', $generator->generate($prop));
     $prop = PhpParameter::create('foo')->setValue(null);
     $this->assertEquals('$foo = null', $generator->generate($prop));
     $prop = PhpParameter::create('foo')->setValue(PhpConstant::create('BAR'));
     $this->assertEquals('$foo = BAR', $generator->generate($prop));
     $prop = PhpParameter::create('foo')->setExpression("['bar' => 'baz']");
     $this->assertEquals('$foo = [\'bar\' => \'baz\']', $generator->generate($prop));
 }
Esempio n. 14
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}");
 }
Esempio n. 15
0
    public function testObjectParam()
    {
        $expected = '/**
 * @param Request $r
 * @param mixed $a
 * @return Response this method returns a response object
 */';
        $function = PhpFunction::create(self::METHOD)->setType('Response', 'this method returns a response object')->addParameter(PhpParameter::create('r')->setType('Request'))->addParameter(PhpParameter::create('a')->setType('mixed'));
        $function->generateDocblock();
        $this->assertSame($expected, $function->getDocblock()->toString());
    }
Esempio n. 16
0
    $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));
}
Esempio n. 17
0
 /**
  * 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;
 }
 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);
 }
Esempio n. 19
0
 /**
  * @param $name
  * @param OutputInterface $output
  *
  * @return mixed
  */
 private function cronjob($name, $output)
 {
     $path = __DIR__ . "/../Task/Cronjobs/{$name}Cronjob.php";
     if (file_exists($path)) {
         return $output->writeln("Error, file already exists");
     }
     $class = new PhpClass();
     $class->setQualifiedName("Mira\\Task\\Cronjobs\\{$name}Cronjob")->setDescription($this->descr)->setMethod(PhpMethod::create("getRunTimes")->setVisibility("public")->setStatic(true)->setDescription("Defines how often the cronjob runs, every 1 second, every 60 seconds, every 86400 seconds, etc.")->setBody("return 0; // Never runs"))->setMethod(PhpMethod::create("execute")->setVisibility("public")->setStatic(true)->setDescription("Executes the cronjob task")->addParameter(PhpParameter::create("pid"))->addParameter(PhpParameter::create("md5"))->addParameter(PhpParameter::create("app")->setType("MiraApp"))->setBody("exit(); // Keep this at the bottom, to make sure the fork exits"))->declareUse('Mira\\MiraApp');
     $generator = new CodeFileGenerator();
     $code = $generator->generate($class);
     $formatter = new Formatter();
     $code = $formatter->format($code);
     file_put_contents($path, $code);
     $output->writeln("Cronjob created: {$path}");
 }
Esempio n. 20
0
 /**
  *
  * @return PhpParameter
  */
 protected static function createParameter(\ReflectionParameter $parameter)
 {
     return PhpParameter::fromReflection($parameter);
 }