/** * Generate a CREATE TABLE statement * * @return string */ public static function generateCreateTableStatement() { $tableName = self::getEntityType(); // Create table $sql = sprintf('CREATE TABLE `%s` (' . PHP_EOL, $tableName); $primaryKeys = array(); // Add columns $reflectionClass = new Reflection\ReflectionClass(self::getClassNameOfEntityDefinition()); foreach ($reflectionClass->getProperties() as $property) { $definition = $property->getAnnotation('HynageColumn'); if (!is_array($definition)) { continue; } $name = isset($definition['name']) ? $definition['name'] : ltrim($property->name, '_'); $default = $property->getAnnotation('HynageColumnDefault'); if (isset($definition['type'])) { if ($definition['type'] == 'enum') { if (!isset($definition['values'])) { throw new Entity\InvalidDefinitionException("Missing 'values' property in @HynageColumn annotation for enum data type {$name}."); } $enumValues = array(); foreach (explode(',', $definition['values']) as $enumValue) { $enumValues[] = "'{$enumValue}'"; } $definition['type'] = 'ENUM(' . join(', ', $enumValues) . ')'; unset($definition['length']); } else { $definition['type'] = strtoupper($definition['type']); } } $sql .= sprintf(' `%s` %s%s%s%s%s%s,' . PHP_EOL, $name, isset($definition['type']) ? $definition['type'] : 'VARCHAR', isset($definition['length']) ? sprintf('(%d)', $definition['length']) : '', $property->hasAnnotation('HynageColumnUnsigned') ? ' UNSIGNED' : '', $property->hasAnnotation('HynageColumnNotNull') ? ' NOT NULL' : ' NULL', null === $default ? '' : sprintf(' DEFAULT \'%s\'', $default), $property->hasAnnotation('HynageColumnAutoIncrement') ? ' AUTO_INCREMENT' : ''); if ($property->hasAnnotation('HynageColumnPrimary')) { $primaryKeys[] = sprintf('`%s`', $name); } } // Add primary key(s) $sql .= sprintf(' PRIMARY KEY (%s)' . PHP_EOL, join(', ', $primaryKeys)); $sql .= ');'; return $sql; }