Create Ng-Rest-Model, Controller and Api for an existing Database-Table.

@return number
494241
public function actionCreate()
    {
        // 1. ask for module
        if ($this->moduleName === null) {
            Console::clearScreenBeforeCursor();
            $this->moduleName = $this->selectModule(['onlyAdmin' => $this->hideFrontendModules, 'hideCore' => $this->hideCoreModules, 'text' => 'Select the Module where the CRUD files should be saved:']);
        }
        
        // 2. ask for sql table
        if ($this->dbTableName === null) {
            $this->dbTableName = $this->prompt('Enter the name of the database table to generate the model for (? to see all tables):', ['required' => true, 'validator' => function ($input, &$error) {
                if ($input == '?') {
                    foreach ($this->getSqlTablesArray() as $table) {
                        $this->outputInfo("- " . $table);
                    }
                    return false;
                }
                
                if (!isset($this->getSqlTablesArray()[$input])) {
                    $error = "Table '$input' does not exists. Type '?' to see all tables.";
                    return false;
                }
                
                return true;
            }]);
        }
        
        // 3. ask for model name
        if ($this->modelName === null) {
            $modelSelection = true;
            while ($modelSelection) {
                $modelName = $this->prompt('Model Name (e.g. Album):', ['required' => true, 'default' => $this->getModelNameSuggestion()]);
                $camlizeModelName = Inflector::camelize($modelName);
                if ($modelName !== $camlizeModelName) {
                    if ($this->confirm("We have camlized the model name to '$camlizeModelName' do you want to continue with this name?")) {
                        $modelName = $camlizeModelName;
                        $modelSelection = false;
                    }
                } else {
                    $modelSelection = false;
                }
                $this->modelName = $modelName;
            }
        }
        
        // 4. ask for api endpoint name
        if ($this->apiEndpoint === null) {
            $this->apiEndpoint = $this->prompt('Api Endpoint:', ['required' => true, 'default' => $this->getApiEndpointSuggestion()]);
        }

        // 5. ask for i18n
        if ($this->enableI18n === null) {
            $this->enableI18n = $this->confirm("Would you like to enable i18n field input for text fields? Only required for multilingual pages.");
        }

        $this->ensureBasePathAndNamespace();
        
        $files = [];
        
        // api content

        $files['api'] = [
            'path' => $this->getBasePath() . DIRECTORY_SEPARATOR . 'apis',
            'fileName' => $this->getModelNameCamlized() . 'Controller.php',
            'content' => $this->generateApiContent($this->getNamespace() . '\\apis', $this->getModelNameCamlized() . 'Controller', $this->getAbsoluteModelNamespace()),
        ];
        
        // controller

        $files['controller'] = [
            'path' =>  $this->getBasePath() . DIRECTORY_SEPARATOR . 'controllers',
            'fileName' => $this->getModelNameCamlized() . 'Controller.php',
            'content' => $this->generateControllerContent($this->getNamespace() . '\\controllers', $this->getModelNameCamlized() . 'Controller', $this->getAbsoluteModelNamespace()),
        ];
        
        // model

        $files['model'] = [
            'path' =>  $this->getModelBasePath() . DIRECTORY_SEPARATOR . 'models',
            'fileName' => $this->getModelNameCamlized() . '.php',
            'content' => $this->generateModelContent(
                $this->getModelNamespace() . '\\models',
                $this->getModelNameCamlized(),
                $this->apiEndpoint,
                $this->getDbTableShema(),
                $this->enableI18n
             ),
        ];
        
        foreach ($files as $file) {
            $this->generateFile($file);
        }
        
        return $this->outputSuccess($this->generateBuildSummery($this->apiEndpoint, $this->getNamespace() . '\\apis\\' . $this->getModelNameCamlized() . 'Controller', $this->getModelNameCamlized(), $this->getSummaryControllerRoute()));
    }
1364356
protected function createSchema()
    {
        $schema = new ModelSchema("tblAuthenticationRole");
        $schema->addColumn(
            new AutoIncrementColumn("RoleID"),
            new StringColumn("RoleName", 40)
        );

        $schema->labelColumnName = "RoleName";

        return $schema;
    }
914531
public function createDatabaseObject()
    {
        $dbname = trim($this->getSubmitValue('dbname'));
        if (empty($dbname)) // disallow database object creation w/ no selected database
        {
            throw new Exception("No database name");
        }

        $adapter = $this->getSubmitValue('adapter');
        $port = Adapter::getDefaultPortForAdapter($adapter);

        $host = $this->getSubmitValue('host');
        $tables_prefix = $this->getSubmitValue('tables_prefix');
        
        $dbInfos = array(
            'host'          => (is_null($host)) ? $host : trim($host),
            'username'      => $this->getSubmitValue('username'),
            'password'      => $this->getSubmitValue('password'),
            'dbname'        => $dbname,
            'tables_prefix' => (is_null($tables_prefix)) ? $tables_prefix : trim($tables_prefix),
            'adapter'       => $adapter,
            'port'          => $port,
            'schema'        => Config::getInstance()->database['schema'],
            'type'          => $this->getSubmitValue('type')
        );

        if (($portIndex = strpos($dbInfos['host'], '/')) !== false) {
            // unix_socket=/path/sock.n
            $dbInfos['port'] = substr($dbInfos['host'], $portIndex);
            $dbInfos['host'] = '';
        } else if (($portIndex = strpos($dbInfos['host'], ':')) !== false) {
            // host:port
            $dbInfos['port'] = substr($dbInfos['host'], $portIndex + 1);
            $dbInfos['host'] = substr($dbInfos['host'], 0, $portIndex);
        }

        try {
            @Db::createDatabaseObject($dbInfos);
        } catch (Zend_Db_Adapter_Exception $e) {
            $db = Adapter::factory($adapter, $dbInfos, $connect = false);

            // database not found, we try to create  it
            if ($db->isErrNo($e, '1049')) {
                $dbInfosConnectOnly = $dbInfos;
                $dbInfosConnectOnly['dbname'] = null;
                @Db::createDatabaseObject($dbInfosConnectOnly);
                @DbHelper::createDatabase($dbInfos['dbname']);

                // select the newly created database
                @Db::createDatabaseObject($dbInfos);
            } else {
                throw $e;
            }
        }

        return $dbInfos;
    }
216384
public function createModel()
    {
        $file = '<?php'.$this->namespace.LF.LF;

        $file .= '/**'.LF;
        $file .= ' * Eloquent class to describe the '.$this->table.' table'.LF;
        $file .= ' *'.LF;
        $file .= ' * automatically generated by ModelGenerator.php'.LF;
        $file .= ' */'.LF;

        // a new class that extends the provided baseModel
        $file .= 'class '.$this->class.' extends '.$this->baseModel.LF;
        $file .= '{'.LF;

        // the name of the mysql table
        $file .= TAB.'protected $table = '.StringUtils::singleQuote($this->table).';'.LF.LF;

        // primary key defaults to "id"
        if ($this->primaryKey !== 'id') {
            $file .= TAB.'public $primaryKey = '.StringUtils::singleQuote($this->primaryKey).';'.LF.LF;
        }

        // timestamps defaults to true
        if (!$this->timestamps) {
            $file .= TAB.'public $timestamps = '.var_export($this->timestamps, true).';'.LF.LF;
        }

        // incrementing defaults to true
        if (!$this->incrementing) {
            $file .= TAB.'public $incrementing = '.var_export($this->incrementing, true).';'.LF.LF;
        }

        // all date fields
        if (!empty($this->dates)) {
            $file .= TAB.'public function getDates()'.LF;
            $file .= TAB.'{'.LF;
            $file .= TAB.TAB.'return array('.StringUtils::implodeAndQuote(', ', $this->dates).');'.LF;
            $file .= TAB.'}'.LF.LF;
        }

        // most fields are considered as fillable
        $wrap = TAB.'protected $fillable = array('.StringUtils::implodeAndQuote(', ', $this->fillable).');'.LF.LF;
        $file .= wordwrap($wrap, ModelGenerator::$lineWrap, LF.TAB.TAB);

        // except for the hidden ones
        if (!empty($this->hidden)) {
            $file .= TAB.'protected $hidden = array('.StringUtils::implodeAndQuote(', ', $this->hidden).');'.LF.LF;
        }

        // add all relations
        $file .= rtrim($this->relations).LF; // remove one LF from end

        // close the class
        $file .= '}'.LF;

        $this->fileContents = $file;
    }
1262129
def create(self):
    
    data = data={"db-name":self.db}
    self.rest('POST', self.uri_str, status_codes=(200,201), data=data)
    return True
1088486
private function generateController()
    {
        // Generate Controller class
        $controllerInstance = Controller::instance($this->columns, $this->viewType, $this);

        $controllerTemplateDir =
            dirname(dirname(__FILE__)).DS.'src'.DS.'Apps'.DS.'Controllers'.DS;

        $controllerInstance->setControllerTemplatePath($controllerTemplateDir);
        $controllerInstance->setApplicationDirectory($this->applicationDir);

        $controllerInstance->setControllerName($this->controller);
        $controllerInstance->setModelName($this->model);
        $controllerInstance->updateTemplate();
        $controllerInstance->generateControllerTemplate();

        $controllerInstance->generate();

        $this->info("Controller $this->controller Generated Successfully!");
    }
371456
public function createInstance()
    {
        switch ($this->method) {
            case 'addBigIntegerColumn':
            case 'addBinaryColumn':
            case 'addBooleanColumn':
            case 'addDateColumn':
            case 'addDateTimeColumn':
            case 'addDecimalColumn':
            case 'addFloatColumn':
            case 'addIntegerColumn':
            case 'addSmallIntegerColumn':
            case 'addStringColumn':
            case 'addTextColumn':
            case 'addTimeColumn':
                $namespace = 'Rentgen\\Database\\Column\\';
                $class = $namespace . ltrim($this->method, 'add');
                $options = isset($this->params[1]) ? $this->params[1] : array();

                if ('addStringColumn' === $this->method && !isset($options['limit'])) {
                    $options['limit'] = 255;
                }
                $column = new $class($this->params[0], $options);
                break;
            case 'addCustomColumn':
                $options = isset($this->params[2]) ? $this->params[2] : [];
                $column = new CustomColumn($this->params[0], $this->params[1], $options);
                break;
            default:
                throw new \Exception(sprintf("Unsupported method " . $this->method));
        }

        if (isset($options['comment'])) {
            $column->setDescription($options['comment']);
        }

        return $column;
    }
635049
private function generateController()
    {
        // Figure out the naming
        $controller = Str::plural(ucfirst($this->argument('model')));
        $path = 'app/Http/Controllers/Admin/'.$controller.'.php';
        $file = base_path().'/'.$path;

        // Copy the stub over
        if (!file_exists(dirname($file))) {
            mkdir(dirname($file), 0744, true);
        }
        if (file_exists($file)) {
            return $this->comment('Controller already exists: '.$path);
        }
        file_put_contents($file, str_replace('{{controller}}', $controller, file_get_contents($this->stubs.'/controller.stub')));
        $this->info('Controller created: '.$path);
    }
1322867
public static function buildTableMap()
    {
      $dbMap = Propel::getDatabaseMap(BaseRolePeer::DATABASE_NAME);
      if (!$dbMap->hasTable(BaseRolePeer::TABLE_NAME)) {
        $dbMap->addTableObject(new \Slashworks\BackendBundle\Model\map\RoleTableMap());
      }
    }
1101176
function create()
    {
        //Tablela ARTICLE
        $this->db->query("CREATE TABLE `article` (
                          `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                          `category` int(11) NOT NULL DEFAULT '1',
                          `status` int(11) NOT NULL,
                          `author` int(11) NOT NULL DEFAULT '1',
                          `rateup` int(11) NOT NULL DEFAULT '0',
                          `ratedown` int(11) NOT NULL DEFAULT '0',
                          `access` int(11) NOT NULL DEFAULT '0',
                          `pubdate` datetime DEFAULT NULL,
                          `editdate` datetime DEFAULT NULL,
                          `link` varchar(300) DEFAULT NULL,
                          `tags` varchar(300) DEFAULT NULL,
                          `title` varchar(300) DEFAULT NULL,
                          `media` text,
                          `resume` text,
                          PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8");

        //Tablela ARTICLECONTENT
            $this->db->query("CREATE TABLE `articlecontent` (
                          `article` int(10) unsigned NOT NULL,
                          `editdate` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
                          `content` longtext NOT NULL,
                          KEY `article` (`article`),
                          CONSTRAINT `articlecontent_ibfk_1` FOREIGN KEY (`article`) REFERENCES `article` (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8");

        //Tablela CATEGORY
            $this->db->query("CREATE TABLE `category` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `name` varchar(200) NOT NULL,
                          `description` varchar(500) NOT NULL,
                          PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=latin1");

        //Tablela STATUS
            $this->db->query("CREATE TABLE `status` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `name` varchar(200) NOT NULL,
                          `description` varchar(500) NOT NULL,
                          PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=latin1");

        //Tablela STATUS - INSERT
            $this->db->query("INSERT INTO `status` (`id`, `name`, `description`) VALUES
                        (1, 'Publicar imediatamente', 'Artigo publicado imediatamente depois de criado/editado.'),
                        (2, 'Salvar como Rascunho', 'Mantém como um rascunho para futura edição (estacionado)'),
                        (3, 'Deletar ou Desabilitar', 'Sinaliza que o artigo está deletado, porém, se mantém salvo para futura auditoria. '),
                        (4, 'Acesso Restrito - logado', 'Permite acesso somente a leitores logados.'),
                        (5, 'Editando...',  'O registro fica reservado para edição por 24 horas.'),
                        (6, 'Livre para reúso', 'Registro usado anteriormente, porém, livre para reúso.')");

        //Tablela USUARIO
            $this->db->query("CREATE TABLE `usuario` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `login` varchar(255) DEFAULT NULL,
                          `senha` varchar(300) DEFAULT NULL,
                          `nome` varchar(255) DEFAULT NULL,
                          `token` varchar(200) DEFAULT NULL,
                          `vida` int(11) unsigned DEFAULT NULL,
                          `nivel` varchar(45) DEFAULT NULL COMMENT '[A]dmin, [E]ditor, [G]uest',
                          `status` char(1) DEFAULT NULL COMMENT '[A]ctive, [D]isable',
                          PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8");

        //Tablela USUARIO - INSERT
            $this->db->query("INSERT INTO `usuario` (`id`, `login`, `senha`, `nome`, `token`, `vida`, `nivel`, `status`) VALUES
                        (1, 'admin',  'admin#123',  'Administrator',  'DrFol:LeinC%[4CBVcT$hW<mdLEXE)vdCiZVV%Vq', 908,  'A',  'A'),
                        (2, 'editor', 'editor#123', 'Editor', 'v!BPf#hePX30Ks>GK~çjj',  908,  'E',  'A'),
                        (3, 'jessica',  'jessica#123',  'Jessica Mendes', '=+$Wr%yLEbxe7P11iWm1=d)Y@O%47Vow(2r{mv*u', 908,  'A',  'A'),
                        (5, 'guest',  'guest#123',  'Guest',  'IK:QernGB9azWQuh-A6BD',  0,  'G',  'A'),
                        (6, 'test', 'test#123', 'Disabled User',  '![vw*$3lP_z!#IVfe.#n8NiTKBE8<F*=40/B5@tq', 908,  'A',  'D'),
                        (7, 'evora',  'evora123', 'Evora Simpson Smith',  'sadkljhsad9sa04)(sadjhd',  908,  'A',  'A')");

        //Tablela USUARIOPAR - PARAMETROS DE USUÁRIOS
            $this->db->query("CREATE TABLE `usuariopar` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        `usuario` int(11) NOT NULL,
                        `parametro` varchar(100) NOT NULL,
                        `valor` varchar(1000) NOT NULL,
                        PRIMARY KEY (`id`)
                      ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Lista de parâmetros extras para cada usuário (opcional e varia entre usuários)'");

        //Tabela ACCESS
            $this->db->query("CREATE TABLE `access` (
                        `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                        `data` datetime NOT NULL,
                        `ip` varchar(100) NOT NULL,
                        `uri` varchar(300) NOT NULL,
                        `method` varchar(20) NOT NULL,
                        `agent` varchar(500) NOT NULL,
                        PRIMARY KEY (`id`)
                      ) ENGINE=MyISAM DEFAULT CHARSET=utf8");
    }
1017974
protected function createRequest()
    {
        $request = $this->requestFactory->createRequest($this->method, $this->getEndpoint());

        return $this->queryHelper->applyToRequest($request);
    }
2051
public function setup(): Result
    {
        $result = new Result();
        try {
            $this->connect();
            $connection = DriverManager::getConnection(['pdo' => $this->databaseHandle]);
        } catch (Exception | FilesException |DBALException $exception) {
            $result->addError(new Error($exception->getMessage(), $exception->getCode(), [], 'Connection failed'));
            return $result;
        }

        try {
            $tablesExist = $connection->getSchemaManager()->tablesExist([$this->cacheTableName, $this->tagsTableName]);
        } /** @noinspection PhpRedundantCatchClauseInspection */ catch (DBALException $exception) {
            $result->addError(new Error($exception->getMessage(), $exception->getCode(), [], 'Connection failed'));
            return $result;
        }
        if ($tablesExist) {
            $result->addNotice(new Notice('Tables "%s" and "%s" (already exists)', null, [$this->cacheTableName, $this->tagsTableName]));
        } else {
            $result->addNotice(new Notice('Creating database tables "%s" & "%s"...', null, [$this->cacheTableName, $this->tagsTableName]));
        }

        $fromSchema = $connection->getSchemaManager()->createSchema();
        $schemaDiff = (new Comparator())->compare($fromSchema, $this->getCacheTablesSchema());

        try {
            $statements = $schemaDiff->toSaveSql($connection->getDatabasePlatform());
        } catch (DBALException $exception) {
            $result->addError(new Error($exception->getMessage(), $exception->getCode(), [], 'Connection failed'));
            return $result;
        }
        if ($statements === []) {
            $result->addNotice(new Notice('Table schema is up to date, no migration required'));
            return $result;
        }
        $connection->beginTransaction();
        try {
            foreach ($statements as $statement) {
                $result->addNotice(new Notice('<info>++</info> %s', null, [$statement]));
                $connection->exec($statement);
            }
            $connection->commit();
        } catch (\Exception $exception) {
            try {
                $connection->rollBack();
            } catch (\Exception $exception) {
            }
            $result->addError(new Error('Exception while trying to setup PdoBackend: %s', $exception->getCode(), [$exception->getMessage()]));
        }
        return $result;
    }
1230454
protected function create()
	{
		// Only allow creation with new object, otherwise: clone first, create later
		if ( ! $this->is_new())
		{
			return false;
		}

		$this->observe('before_insert');

		// Set all current values
		$query = Query::forge(get_called_class(), static::connection(true));
		$primary_key = static::primary_key();
		$properties  = array_keys(static::properties());
		foreach ($properties as $p)
		{
			if ( ! (in_array($p, $primary_key) and is_null($this->{$p})))
			{
				$query->set($p, $this->{$p});
			}
		}

		// Insert!
		$id = $query->insert();

		// when there's one PK it might be auto-incremented, get it and set it
		if (count($primary_key) == 1 and $id !== false)
		{
			$pk = reset($primary_key);
			// only set it if it hasn't been set manually
			is_null($this->{$pk}) and $this->{$pk} = $id;
		}

		// update the original properties on creation and cache object for future retrieval in this request
		$this->_is_new = false;
		$this->_original = $this->_data;
		static::$_cached_objects[get_class($this)][static::implode_pk($this)] = $this;

		$this->observe('after_insert');

		return $id !== false;
	}
831477
private function generate()
    {
        $schema = [];

        foreach ($this->getTables() as $table) {
            $schema[$table] = $this->getTableDefinition($table);
        };

        foreach (array_keys($schema) as $table) {
            $constraints = $this->driver->getConstraints($table);

            foreach ($constraints as $constraint) {
                if (false === empty($constraint['REF_TABLE'])) {
                    $schema[$table]['properties'][$constraint['REF_TABLE']] = $this->mapConstraint($constraint);
                }
            }
        }

        return $schema;
    }
64982
public function create()
  {
    $uses = [
      'Phrest\API\DI\PhrestDIInterface',
      'Phrest\SDK\PhrestSDK',
      'Phrest\SDK\Request\AbstractRequest',
      $this->namespace . '\\' . Generator::$name . 'API'
    ];

    foreach($this->requests as $request)
    {
      $uses[] = $request->getNamespace() . '\\' . $request->getName();
    }

    $class = ClassGen::classGen(
      $this->name,
      $this->namespace . '\\' . $this->version,
      $uses,
      'PhrestSDK'
    );

    $di = new ParameterGenerator('di', 'PhrestDIInterface');
    $constructor = ClassGen::constructor([$di]);
    $constructor->setBody($this->getConstructorBody());
    $class->addMethodFromGenerator($constructor);

    $abstractRequest = new ParameterGenerator('request', 'AbstractRequest');
    $injectDependencies = ClassGen::method(
      'injectDependencies',
      [$abstractRequest],
      'private',
      'return $request;'
    );
    $docBlock = $injectDependencies->getDocBlock();
    $docBlock->setTag(new GenericTag('return', 'AbstractRequest'));
    $class->addMethodFromGenerator($injectDependencies);

    foreach($this->requests as $request)
    {
      $getRequest = ClassGen::method(
        'get' . ucfirst($request->getName()),
        [],
        'public',
        'return $this->injectDependencies(new ' . $request->getName() . '());'
      );
      $getRequest->getDocBlock()->setTag(new GenericTag('return', $request->getName()));
      $class->addMethodFromGenerator($getRequest);
    }

    return $class;
  }
1350499
public function createDatabase(Request $request)
    {
        $dbName = $request->request->get('new_dbname', '');
        /** @var DataboxService $databoxService */
        $databoxService = $this->app['databox.service'];
        $dataTemplate = $request->request->get('new_data_template');


        try {
            $connectionSettings = $this->buildSettingsFromRequest($request);
            $databox = $databoxService->createDatabox(
                $dbName,
                $dataTemplate,
                $this->getAuthenticatedUser(),
                $connectionSettings
            );

            return $this->app->redirectPath('admin_database', [
                'databox_id'  => $databox->get_sbas_id(),
                'success'     => 1,
                'reload-tree' => 1
            ]);
        }
        catch (\InvalidArgumentException $exception) {
            return $this->handleInvalidArgument($exception);
        }
        catch (DBALException $e) {
            return $this->app->redirectPath('admin_databases', ['success' => 0, 'error' => 'database-failed']);
        }
        catch (\Exception $e) {
            return $this->app->redirectPath('admin_databases', [
                'success' => 0,
                'error' => 'base-failed'
            ]);
        }
    }
1044197
public function build(): RequestDatabaseRequest
	{
		$instance = new RequestDatabaseRequest();
		if ($this->securityOrigin === null) {
			throw new BuilderException('Property [securityOrigin] is required.');
		}
		$instance->securityOrigin = $this->securityOrigin;
		if ($this->databaseName === null) {
			throw new BuilderException('Property [databaseName] is required.');
		}
		$instance->databaseName = $this->databaseName;
		return $instance;
	}