public function testDefaultNotEmptyArray() { $property = new PhpProperty('fooArray'); $visitor = new DefaultVisitor(); $property->setDefaultValue(array("some value")); $visitor->visitProperty($property); $this->assertContains("some value", $visitor->getContent()); }
/** * @param PhpProperty $a * @param PhpProperty $b */ public function compare($a, $b) { 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 visitProperty(Property $node) { $prop = $node->props[0]; $p = new PhpProperty($prop->name); $p->setStatic($node->isStatic()); $p->setVisibility($this->getVisibility($node)); $this->parseValue($p, $prop); $this->parseMemberDocblock($p, $node->getDocComment()); $this->struct->setProperty($p); }
public function testSetGetDefaultValue() { $prop = new PhpProperty('needsName'); $this->assertNull($prop->getDefaultValue()); $this->assertFalse($prop->hasDefaultValue()); $this->assertSame($prop, $prop->setDefaultValue('foo')); $this->assertEquals('foo', $prop->getDefaultValue()); $this->assertTrue($prop->hasDefaultValue()); $this->assertSame($prop, $prop->unsetDefaultValue()); $this->assertNull($prop->getDefaultValue()); $this->assertFalse($prop->hasDefaultValue()); }
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); }
/** * @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 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'))); }
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 testDefaultPropertyComparator() { $list = new ArrayList(); $list->add(PhpProperty::create('arr')->setVisibility(PhpProperty::VISIBILITY_PRIVATE)); $list->add(PhpProperty::create('bar')->setVisibility(PhpProperty::VISIBILITY_PROTECTED)); $list->add(PhpProperty::create('foo')); $list->add(PhpProperty::create('baz')); $list->sort(new DefaultPropertyComparator()); $ordered = $list->map(function ($item) { return $item->getName(); })->toArray(); $this->assertEquals(['baz', 'foo', 'bar', 'arr'], $ordered); }
public function testValues() { $generator = new ModelGenerator(); $prop = PhpProperty::create('foo')->setValue('string'); $this->assertEquals('public $foo = \'string\';' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(300); $this->assertEquals('public $foo = 300;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(162.5); $this->assertEquals('public $foo = 162.5;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(true); $this->assertEquals('public $foo = true;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(false); $this->assertEquals('public $foo = false;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(null); $this->assertEquals('public $foo = null;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setValue(PhpConstant::create('BAR')); $this->assertEquals('public $foo = BAR;' . "\n", $generator->generate($prop)); $prop = PhpProperty::create('foo')->setExpression("['bar' => 'baz']"); $this->assertEquals('public $foo = [\'bar\' => \'baz\'];' . "\n", $generator->generate($prop)); }
public function testEmptyProperty() { $property = new PhpProperty(self::PROP); $property->generateDocblock(); $this->assertTrue($property->getDocblock()->isEmpty()); }
protected function getProperty(Property $node) { $prop = $node->props[0]; $p = new PhpProperty($prop->name); $default = $prop->default; if ($default !== null) { $p->setDefaultValue($this->getValue($default)); } $p->setStatic($node->isStatic()); $p->setVisibility($this->getVisibility($node)); $this->parseMemberDocblock($p, $node->getDocComment()); return $p; }
/** * @expectedException \InvalidArgumentException */ public function testInvalidValue() { PhpProperty::create('x')->setValue(new \stdClass()); }
/** * Adds a property * * @param PhpProperty $property * @return $this */ public function setProperty(PhpProperty $property) { $property->setParent($this); $this->properties->set($property->getName(), $property); return $this; }
/** * * @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; }
/** * @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}"); }
/** * @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}"); }
/** * * @return PhpProperty */ protected static function createProperty(\ReflectionProperty $property) { return PhpProperty::fromReflection($property); }
public function testProperties() { $class = new PhpClass(); $this->assertEquals(array(), $class->getProperties()); $this->assertSame($class, $class->setProperty($prop = new PhpProperty('foo'))); $this->assertSame(array('foo' => $prop), $class->getProperties()); $this->assertTrue($class->hasProperty('foo')); $this->assertSame($class, $class->removeProperty('foo')); $this->assertEquals(array(), $class->getProperties()); $prop = new PhpProperty('bam'); $class->setProperty($prop); $this->assertTrue($class->hasProperty($prop)); $this->assertSame($class, $class->removeProperty($prop)); $class->setProperty($orphaned = new PhpProperty('orphaned')); $this->assertSame($class, $orphaned->getParent()); $this->assertSame($orphaned, $class->getProperty('orphaned')); $this->assertSame($orphaned, $class->getProperty($orphaned)); $this->assertEmpty($class->getProperty('prop-not-found')); $this->assertTrue($class->hasProperty($orphaned)); $this->assertSame($class, $class->setProperties([$prop, $prop2 = new PhpProperty('bar')])); $this->assertSame(['bam' => $prop, 'bar' => $prop2], $class->getProperties()); $this->assertNull($orphaned->getParent()); }
public function testProperties() { $class = new PhpClass(); $this->assertTrue($class->getProperties()->isEmpty()); $this->assertSame($class, $class->setProperty($prop = new PhpProperty('foo'))); $this->assertSame(['foo' => $prop], $class->getProperties()->toArray()); $this->assertTrue($class->hasProperty('foo')); $this->assertSame($class, $class->removeProperty('foo')); $this->assertTrue($class->getProperties()->isEmpty()); $prop = new PhpProperty('bam'); $class->setProperty($prop); $this->assertTrue($class->hasProperty($prop)); $this->assertSame($class, $class->removeProperty($prop)); $class->setProperty($orphaned = new PhpProperty('orphaned')); $this->assertSame($class, $orphaned->getParent()); $this->assertSame($orphaned, $class->getProperty('orphaned')); $this->assertSame($orphaned, $class->getProperty($orphaned)); $this->assertTrue($class->hasProperty($orphaned)); $this->assertSame($class, $class->setProperties([$prop, $prop2 = new PhpProperty('bar')])); $this->assertSame(['bam' => $prop, 'bar' => $prop2], $class->getProperties()->toArray()); $this->assertEquals(['bam', 'bar'], $class->getPropertyNames()->toArray()); $this->assertNull($orphaned->getParent()); $this->assertFalse($class->getProperties()->isEmpty()); $class->clearProperties(); $this->assertTrue($class->getProperties()->isEmpty()); try { $this->assertEmpty($class->getProperty('prop-not-found')); } catch (\InvalidArgumentException $e) { $this->assertNotNull($e); } }
public function visitProperty(PhpProperty $property) { $this->visitDocblock($property->getDocblock()); $this->writer->write($property->getVisibility() . ' ' . ($property->isStatic() ? 'static ' : '') . '$' . $property->getName()); if ($property->hasDefaultValue()) { $this->writer->write(' = ' . $this->getPhpExport($property->getDefaultValue())); } $this->writer->writeln(';'); }
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); $schemaManager = $conn->getSchemaManager(); foreach ($schemaManager->listTables() as $table) { $tableName = $table->getName(); $tableDescriptor = new Table($table); $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);';