/** * @return string * @throws \Phalcon\Builder\BuilderException */ public function build() { if ($this->options->contains('directory')) { $this->path->setRootPath($this->options->get('directory')); } $namespace = ''; if ($this->options->contains('namespace') && $this->checkNamespace($this->options->get('namespace'))) { $namespace = 'namespace ' . $this->options->get('namespace') . ';' . PHP_EOL . PHP_EOL; } $baseClass = $this->options->get('baseClass', '\\Phalcon\\Mvc\\Controller'); if (!($controllersDir = $this->options->get('controllersDir'))) { $config = $this->getConfig(); if (!isset($config->application->controllersDir)) { throw new BuilderException('Please specify a controller directory.'); } $controllersDir = $config->application->controllersDir; } if (!$this->options->contains('name')) { throw new BuilderException('The controller name is required.'); } $name = str_replace(' ', '_', $this->options->get('name')); $className = Utils::camelize($name); // Oops! We are in APP_PATH and try to get controllersDir from outside from project dir if ($this->isConsole() && substr($controllersDir, 0, 3) === '../') { $controllersDir = ltrim($controllersDir, './'); } $controllerPath = rtrim($controllersDir, '\\/') . DIRECTORY_SEPARATOR . $className . "Controller.php"; $code = "<?php\n\n" . $namespace . "class " . $className . "Controller extends " . $baseClass . "\n{\n\n\tpublic function indexAction()\n\t{\n\n\t}\n\n}\n\n"; $code = str_replace("\t", " ", $code); if (file_exists($controllerPath)) { if ($this->options->contains('force') && !is_writable($controllerPath)) { throw new BuilderException(sprintf('Unable to write to %s. Check write-access of a file.', $controllerPath)); } else { throw new BuilderException(sprintf('The Controller %s already exists.', $name)); } } if (!@file_put_contents($controllerPath, $code)) { throw new BuilderException(sprintf('Unable to write to %s.', $controllerPath)); } if ($this->isConsole()) { $this->_notifySuccess(sprintf('Controller "%s" was successfully created.', $name)); } return $className . 'Controller.php'; }
/** * Generate models */ public function createAction() { if ($this->request->isPost()) { $force = $this->request->getPost('force', 'int'); $schema = $this->request->getPost('schema'); $directory = $this->request->getPost('directory'); $namespace = $this->request->getPost('namespace'); $tableName = $this->request->getPost('tableName'); $genSettersGetters = $this->request->getPost('genSettersGetters', 'int'); $foreignKeys = $this->request->getPost('foreignKeys', 'int'); $defineRelations = $this->request->getPost('defineRelations', 'int'); $mapColumn = $this->request->getPost('mapcolumn', 'int'); try { $component = '\\Phalcon\\Builder\\Model'; if ($tableName == 'all') { $component = '\\Phalcon\\Builder\\AllModels'; } $modelBuilder = new $component(array('name' => $tableName, 'force' => $force, 'modelsDir' => $this->modelsDir, 'directory' => $directory, 'foreignKeys' => $foreignKeys, 'defineRelations' => $defineRelations, 'genSettersGetters' => $genSettersGetters, 'namespace' => $namespace, 'schema' => $schema, 'mapColumn' => $mapColumn)); $modelBuilder->build(); if ($tableName == 'all') { if (($n = count($modelBuilder->exist)) > 0) { $mList = implode('</strong>, <strong>', $modelBuilder->exist); if ($n == 1) { $notice = 'Model <strong>' . $mList . '</strong> ' . 'was skipped because it already exists!'; } else { $notice = 'Models <strong>' . $mList . '</strong> ' . 'were skipped because they already exists!'; } $this->flash->notice($notice); } } if ($tableName == 'all') { $message = 'Models were created successfully.'; } else { $message = sprintf('Model "%s" was created successfully', Utils::camelize(str_replace('.php', '', $tableName))); } $this->flash->success($message); } catch (BuilderException $e) { $this->flash->error($e->getMessage()); } } $this->dispatcher->forward(array('controller' => 'models', 'action' => 'list')); }
/** * Generate Scaffold */ public function generateAction() { if ($this->request->isPost()) { $schema = $this->request->getPost('schema', 'string'); $tableName = $this->request->getPost('tableName', 'string'); $version = $this->request->getPost('version', 'string'); $templateEngine = $this->request->getPost('templateEngine'); $force = $this->request->getPost('force', 'int'); $genSettersGetters = $this->request->getPost('genSettersGetters', 'int'); $directory = $this->request->getPost('directory'); $modelsNamespace = $this->request->getPost('modelsNamespace', 'trim'); try { $scaffoldBuilder = new Scaffold(array('name' => $tableName, 'schema' => $schema, 'force' => $force, 'genSettersGetters' => $genSettersGetters, 'directory' => $directory, 'templatePath' => TEMPLATE_PATH, 'templateEngine' => $templateEngine, 'modelsNamespace' => $modelsNamespace)); $scaffoldBuilder->build(); $this->flash->success(sprintf('Scaffold for table "%s" was generated successfully', Utils::camelize($tableName))); return $this->dispatcher->forward(array('controller' => 'scaffold', 'action' => 'index')); } catch (BuilderException $e) { $this->flash->error($e->getMessage()); } } return $this->dispatcher->forward(array('controller' => 'scaffold', 'action' => 'index')); }
/** * Look for table definition modifications and apply to real table * * @param $tableName * @param $definition * * @throws \Phalcon\Db\Exception */ public function morphTable($tableName, $definition) { $defaultSchema = Utils::resolveDbSchema(self::$_databaseConfig); $tableExists = self::$_connection->tableExists($tableName, $defaultSchema); if (isset($definition['columns'])) { if (count($definition['columns']) == 0) { throw new DbException('Table must have at least one column'); } $fields = []; foreach ($definition['columns'] as $tableColumn) { if (!is_object($tableColumn)) { throw new DbException('Table must have at least one column'); } /** * @var \Phalcon\Db\ColumnInterface $tableColumn * @var \Phalcon\Db\ColumnInterface[] $fields */ $fields[$tableColumn->getName()] = $tableColumn; } if ($tableExists == true) { $localFields = []; /** * @var \Phalcon\Db\ColumnInterface[] $description * @var \Phalcon\Db\ColumnInterface[] $localFields */ $description = self::$_connection->describeColumns($tableName, $defaultSchema); foreach ($description as $field) { $localFields[$field->getName()] = $field; } foreach ($fields as $fieldName => $tableColumn) { /** * @var \Phalcon\Db\ColumnInterface $tableColumn * @var \Phalcon\Db\ColumnInterface[] $localFields */ if (!isset($localFields[$fieldName])) { self::$_connection->addColumn($tableName, $tableColumn->getSchemaName(), $tableColumn); } else { $changed = false; if ($localFields[$fieldName]->getType() != $tableColumn->getType()) { $changed = true; } if ($localFields[$fieldName]->getSize() != $tableColumn->getSize()) { $changed = true; } if ($tableColumn->isNotNull() != $localFields[$fieldName]->isNotNull()) { $changed = true; } if ($tableColumn->getDefault() != $localFields[$fieldName]->getDefault()) { $changed = true; } if ($changed == true) { self::$_connection->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn, $tableColumn); } } } foreach ($localFields as $fieldName => $localField) { if (!isset($fields[$fieldName])) { self::$_connection->dropColumn($tableName, null, $fieldName); } } } else { self::$_connection->createTable($tableName, $defaultSchema, $definition); if (method_exists($this, 'afterCreateTable')) { $this->afterCreateTable(); } } } if (isset($definition['references'])) { if ($tableExists == true) { $references = []; foreach ($definition['references'] as $tableReference) { $references[$tableReference->getName()] = $tableReference; } $localReferences = []; $activeReferences = self::$_connection->describeReferences($tableName, $defaultSchema); foreach ($activeReferences as $activeReference) { $localReferences[$activeReference->getName()] = ['referencedTable' => $activeReference->getReferencedTable(), 'columns' => $activeReference->getColumns(), 'referencedColumns' => $activeReference->getReferencedColumns()]; } foreach ($definition['references'] as $tableReference) { if (!isset($localReferences[$tableReference->getName()])) { self::$_connection->addForeignKey($tableName, $tableReference->getSchemaName(), $tableReference); } else { $changed = false; if ($tableReference->getReferencedTable() != $localReferences[$tableReference->getName()]['referencedTable']) { $changed = true; } if ($changed == false) { if (count($tableReference->getColumns()) != count($localReferences[$tableReference->getName()]['columns'])) { $changed = true; } } if ($changed == false) { if (count($tableReference->getReferencedColumns()) != count($localReferences[$tableReference->getName()]['referencedColumns'])) { $changed = true; } } if ($changed == false) { foreach ($tableReference->getColumns() as $columnName) { if (!in_array($columnName, $localReferences[$tableReference->getName()]['columns'])) { $changed = true; break; } } } if ($changed == false) { foreach ($tableReference->getReferencedColumns() as $columnName) { if (!in_array($columnName, $localReferences[$tableReference->getName()]['referencedColumns'])) { $changed = true; break; } } } if ($changed == true) { self::$_connection->dropForeignKey($tableName, $tableReference->getSchemaName(), $tableReference->getName()); self::$_connection->addForeignKey($tableName, $tableReference->getSchemaName(), $tableReference); } } } foreach ($localReferences as $referenceName => $reference) { if (!isset($references[$referenceName])) { self::$_connection->dropForeignKey($tableName, null, $referenceName); } } } } if (isset($definition['indexes'])) { if ($tableExists == true) { $indexes = []; foreach ($definition['indexes'] as $tableIndex) { $indexes[$tableIndex->getName()] = $tableIndex; } $localIndexes = []; $actualIndexes = self::$_connection->describeIndexes($tableName, $defaultSchema); foreach ($actualIndexes as $actualIndex) { $localIndexes[$actualIndex->getName()] = $actualIndex->getColumns(); } foreach ($definition['indexes'] as $tableIndex) { if (!isset($localIndexes[$tableIndex->getName()])) { if ($tableIndex->getName() == 'PRIMARY') { self::$_connection->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex); } else { self::$_connection->addIndex($tableName, $tableColumn->getSchemaName(), $tableIndex); } } else { $changed = false; if (count($tableIndex->getColumns()) != count($localIndexes[$tableIndex->getName()])) { $changed = true; } else { foreach ($tableIndex->getColumns() as $columnName) { if (!in_array($columnName, $localIndexes[$tableIndex->getName()])) { $changed = true; break; } } } if ($changed == true) { if ($tableIndex->getName() == 'PRIMARY') { self::$_connection->dropPrimaryKey($tableName, $tableColumn->getSchemaName()); self::$_connection->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex); } else { self::$_connection->dropIndex($tableName, $tableColumn->getSchemaName(), $tableIndex->getName()); self::$_connection->addIndex($tableName, $tableColumn->getSchemaName(), $tableIndex); } } } } foreach ($localIndexes as $indexName => $indexColumns) { if (!isset($indexes[$indexName])) { self::$_connection->dropIndex($tableName, null, $indexName); } } } } }
public function build() { if (!$this->options->contains('name')) { throw new BuilderException('You must specify the table name'); } if ($this->options->contains('directory')) { $this->path->setRootPath($this->options->get('directory')); } $config = $this->getConfig(); if (!($modelsDir = $this->options->get('modelsDir'))) { if (!isset($config->application->modelsDir)) { throw new BuilderException("Builder doesn't know where is the models directory."); } $modelsDir = $config->application->modelsDir; } $modelsDir = rtrim($modelsDir, '/\\') . DIRECTORY_SEPARATOR; $modelPath = $modelsDir; if (false == $this->isAbsolutePath($modelsDir)) { $modelPath = $this->path->getRootPath($modelsDir); } $methodRawCode = array(); $className = $this->options->get('className'); $modelPath .= $className . '.php'; if (file_exists($modelPath) && !$this->options->contains('force')) { throw new BuilderException(sprintf('The model file "%s.php" already exists in models dir', $className)); } if (!isset($config->database)) { throw new BuilderException('Database configuration cannot be loaded from your config file.'); } if (!isset($config->database->adapter)) { throw new BuilderException("Adapter was not found in the config. " . "Please specify a config variable [database][adapter]"); } $namespace = ''; if ($this->options->contains('namespace') && $this->checkNamespace($this->options->get('namespace'))) { $namespace = 'namespace ' . $this->options->get('namespace') . ';' . PHP_EOL . PHP_EOL; } $genDocMethods = $this->options->get('genDocMethods', false); $useSettersGetters = $this->options->get('genSettersGetters', false); $adapter = $config->database->adapter; $this->isSupportedAdapter($adapter); $adapter = 'Mysql'; if (isset($config->database->adapter)) { $adapter = $config->database->adapter; } if (is_object($config->database)) { $configArray = $config->database->toArray(); } else { $configArray = $config->database; } // An array for use statements $uses = array(); $adapterName = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter; unset($configArray['adapter']); /** @var \Phalcon\Db\Adapter\Pdo $db */ $db = new $adapterName($configArray); $initialize = array(); if ($this->options->contains('schema')) { $schema = $this->options->get('schema'); if ($schema != $config->database->dbname) { $initialize['schema'] = $this->snippet->getThisMethod('setSchema', $schema); } } elseif ($adapter == 'Postgresql') { $schema = 'public'; $initialize['schema'] = $this->snippet->getThisMethod('setSchema', $schema); } else { $schema = $config->database->dbname; } $table = $this->options->get('name'); if ($this->options->get('fileName') != $table && !isset($initialize['schema'])) { $initialize[] = $this->snippet->getThisMethod('setSource', '\'' . $table . '\''); } if (!$db->tableExists($table, $schema)) { throw new BuilderException(sprintf('Table "%s" does not exist.', $table)); } $fields = $db->describeColumns($table, $schema); foreach ($db->listTables() as $tableName) { foreach ($db->describeReferences($tableName, $schema) as $reference) { if ($reference->getReferencedTable() != $this->options->get('name')) { continue; } $entityNamespace = ''; if ($this->options->contains('namespace')) { $entityNamespace = $this->options->get('namespace') . "\\"; } $refColumns = $reference->getReferencedColumns(); $columns = $reference->getColumns(); $initialize[] = $this->snippet->getRelation('hasMany', $refColumns[0], $entityNamespace . Utils::camelize($tableName), $columns[0], "array('alias' => '" . Utils::camelize($tableName) . "')"); } } foreach ($db->describeReferences($this->options->get('name'), $schema) as $reference) { $entityNamespace = ''; if ($this->options->contains('namespace')) { $entityNamespace = $this->options->get('namespace') . "\\"; } $refColumns = $reference->getReferencedColumns(); $columns = $reference->getColumns(); $initialize[] = $this->snippet->getRelation('belongsTo', $columns[0], $entityNamespace . Utils::camelize($reference->getReferencedTable()), $refColumns[0], "array('alias' => '" . Utils::camelize($reference->getReferencedTable()) . "')"); } if ($this->options->has('hasMany')) { if (count($this->options->get('hasMany'))) { foreach ($this->options->get('hasMany') as $relation) { if (!is_string($relation['fields'])) { continue; } $entityName = $relation['camelizedName']; $entityNamespace = ''; if ($this->options->contains('namespace')) { $entityNamespace = $this->options->get('namespace') . "\\"; $relation['options']['alias'] = $entityName; } $initialize[] = $this->snippet->getRelation('hasMany', $relation['fields'], $entityNamespace . $entityName, $relation['relationFields'], $this->snippet->getRelationOptions(isset($relation['options']) ? $relation["options"]->toArray() : null)); } } } if ($this->options->has('belongsTo')) { if (count($this->options->get('belongsTo'))) { foreach ($this->options->get('belongsTo') as $relation) { if (!is_string($relation['fields'])) { continue; } $entityName = Utils::camelize($relation['referencedModel']); $entityNamespace = ''; if ($this->options->contains('namespace')) { $entityNamespace = $this->options->get('namespace') . "\\"; $relation['options']['alias'] = $entityName; } $initialize[] = $this->snippet->getRelation('belongsTo', $relation['fields'], $entityNamespace . $entityName, $relation['relationFields'], $this->snippet->getRelationOptions(isset($relation['options']) ? $relation["options"]->toArray() : null)); } } } $alreadyInitialized = false; $alreadyValidations = false; $alreadyFind = false; $alreadyFindFirst = false; $alreadyColumnMapped = false; $alreadyGetSourced = false; if (file_exists($modelPath)) { try { $possibleMethods = array(); if ($useSettersGetters) { foreach ($fields as $field) { /** @var \Phalcon\Db\Column $field */ $methodName = Utils::camelize($field->getName()); $possibleMethods['set' . $methodName] = true; $possibleMethods['get' . $methodName] = true; } } $possibleMethods['getSource'] = true; require $modelPath; $linesCode = file($modelPath); $fullClassName = $this->options->get('className'); if ($this->options->contains('namespace')) { $fullClassName = $this->options->get('namespace') . '\\' . $fullClassName; } $reflection = new ReflectionClass($fullClassName); foreach ($reflection->getMethods() as $method) { if ($method->getDeclaringClass()->getName() != $fullClassName) { continue; } $methodName = $method->getName(); if (isset($possibleMethods[$methodName])) { continue; } $indent = PHP_EOL; if ($method->getDocComment()) { $firstLine = $linesCode[$method->getStartLine() - 1]; preg_match('#^\\s+#', $firstLine, $matches); if (isset($matches[0])) { $indent .= $matches[0]; } } $methodDeclaration = join('', array_slice($linesCode, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1)); $methodRawCode[$methodName] = $indent . $method->getDocComment() . PHP_EOL . $methodDeclaration; switch ($methodName) { case 'initialize': $alreadyInitialized = true; break; case 'validation': $alreadyValidations = true; break; case 'find': $alreadyFind = true; break; case 'findFirst': $alreadyFindFirst = true; break; case 'columnMap': $alreadyColumnMapped = true; break; case 'getSource': $alreadyGetSourced = true; break; } } } catch (ReflectionException $e) { } } $validations = array(); foreach ($fields as $field) { if ($field->getType() === Column::TYPE_CHAR) { $domain = array(); if (preg_match('/\\((.*)\\)/', $field->getType(), $matches)) { foreach (explode(',', $matches[1]) as $item) { $domain[] = $item; } } if (count($domain)) { $varItems = join(', ', $domain); $validations[] = $this->snippet->getValidateInclusion($field->getName(), $varItems); } } if ($field->getName() == 'email') { $validations[] = $this->snippet->getValidateEmail($field->getName()); $uses[] = $this->snippet->getUseAs('Phalcon\\Mvc\\Model\\Validator\\Email', 'Email'); } } if (count($validations)) { $validations[] = $this->snippet->getValidationFailed(); } // Check if there has been an extender class $extends = $this->options->get('extends', '\\Phalcon\\Mvc\\Model'); // Check if there have been any excluded fields $exclude = array(); if ($this->options->contains('excludeFields')) { $keys = explode(',', $this->options->get('excludeFields')); if (count($keys) > 0) { foreach ($keys as $key) { $exclude[trim($key)] = ''; } } } $attributes = array(); $setters = array(); $getters = array(); foreach ($fields as $field) { if (array_key_exists(strtolower($field->getName()), $exclude)) { continue; } $type = $this->getPHPType($field->getType()); if ($useSettersGetters) { $attributes[] = $this->snippet->getAttributes($type, 'protected', $field->getName()); $methodName = Utils::camelize($field->getName()); $setters[] = $this->snippet->getSetter($field->getName(), $type, $methodName); if (isset($this->_typeMap[$type])) { $getters[] = $this->snippet->getGetterMap($field->getName(), $type, $methodName, $this->_typeMap[$type]); } else { $getters[] = $this->snippet->getGetter($field->getName(), $type, $methodName); } } else { $attributes[] = $this->snippet->getAttributes($type, 'public', $field->getName()); } } $validationsCode = ''; if ($alreadyValidations == false && count($validations) > 0) { $validationsCode = $this->snippet->getValidationsMethod($validations); } $initCode = ''; if ($alreadyInitialized == false && count($initialize) > 0) { $initCode = $this->snippet->getInitialize($initialize); } $license = ''; if (file_exists('license.txt')) { $license = trim(file_get_contents('license.txt')) . PHP_EOL . PHP_EOL; } if (false == $alreadyGetSourced) { $methodRawCode[] = $this->snippet->getModelSource($this->options->get('name')); } if (false == $alreadyFind) { $methodRawCode[] = $this->snippet->getModelFind($className); } if (false == $alreadyFindFirst) { $methodRawCode[] = $this->snippet->getModelFindFirst($className); } $content = join('', $attributes); if ($useSettersGetters) { $content .= join('', $setters) . join('', $getters); } $content .= $validationsCode . $initCode; foreach ($methodRawCode as $methodCode) { $content .= $methodCode; } $classDoc = ''; if ($genDocMethods) { $classDoc = $this->snippet->getClassDoc($className, $namespace); } if ($this->options->contains('mapColumn') && false == $alreadyColumnMapped) { $content .= $this->snippet->getColumnMap($fields); } $useDefinition = ''; if (!empty($uses)) { $useDefinition = join('', $uses) . PHP_EOL . PHP_EOL; } $abstract = $this->options->contains('abstract') ? 'abstract ' : ''; $code = $this->snippet->getClass($namespace, $useDefinition, $classDoc, $abstract, $className, $extends, $content, $license); if (file_exists($modelPath) && !is_writable($modelPath)) { throw new BuilderException(sprintf('Unable to write to %s. Check write-access of a file.', $modelPath)); } if (!file_put_contents($modelPath, $code)) { throw new BuilderException(sprintf('Unable to write to %s', $modelPath)); } if ($this->isConsole()) { $msgSuccess = ($this->options->contains('abstract') ? 'Abstract ' : '') . 'Model "%s" was successfully created.'; $this->_notifySuccess(sprintf($msgSuccess, Utils::camelize($this->options->get('name')))); } }
public function build() { if ($this->options->contains('directory')) { $this->path->setRootPath($this->options->get('directory')); } $this->options->offsetSet('directory', $this->path->getRootPath()); $config = $this->getConfig(); if (!($modelsDir = $this->options->get('modelsDir'))) { if (!isset($config->application->modelsDir)) { throw new BuilderException("Builder doesn't know where is the models directory."); } $modelsDir = $config->application->modelsDir; } $modelsDir = rtrim($modelsDir, '/\\') . DIRECTORY_SEPARATOR; $modelPath = $modelsDir; if (false == $this->isAbsolutePath($modelsDir)) { $modelPath = $this->path->getRootPath($modelsDir); } $this->options->offsetSet('modelsDir', $modelPath); $forceProcess = $this->options->get('force'); $defineRelations = $this->options->get('defineRelations', false); $defineForeignKeys = $this->options->get('foreignKeys', false); $genSettersGetters = $this->options->get('genSettersGetters', false); $mapColumn = $this->options->get('mapColumn', null); $adapter = $config->database->adapter; $this->isSupportedAdapter($adapter); $adapter = 'Mysql'; if (isset($config->database->adapter)) { $adapter = $config->database->adapter; } if (is_object($config->database)) { $configArray = $config->database->toArray(); } else { $configArray = $config->database; } $adapterName = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter; unset($configArray['adapter']); /** * @var $db \Phalcon\Db\Adapter\Pdo */ $db = new $adapterName($configArray); if ($this->options->contains('schema')) { $schema = $this->options->get('schema'); } else { $schema = Utils::resolveDbSchema($config->database); } $hasMany = array(); $belongsTo = array(); $foreignKeys = array(); if ($defineRelations || $defineForeignKeys) { foreach ($db->listTables($schema) as $name) { if ($defineRelations) { if (!isset($hasMany[$name])) { $hasMany[$name] = array(); } if (!isset($belongsTo[$name])) { $belongsTo[$name] = array(); } } if ($defineForeignKeys) { $foreignKeys[$name] = array(); } $camelCaseName = Utils::camelize($name); $refSchema = $adapter != 'Postgresql' ? $schema : $config->database->dbname; foreach ($db->describeReferences($name, $schema) as $reference) { $columns = $reference->getColumns(); $referencedColumns = $reference->getReferencedColumns(); $referencedModel = Utils::camelize($reference->getReferencedTable()); if ($defineRelations) { if ($reference->getReferencedSchema() == $refSchema) { if (count($columns) == 1) { $belongsTo[$name][] = array('referencedModel' => $referencedModel, 'fields' => $columns[0], 'relationFields' => $referencedColumns[0], 'options' => $defineForeignKeys ? array('foreignKey' => true) : null); $hasMany[$reference->getReferencedTable()][] = array('camelizedName' => $camelCaseName, 'fields' => $referencedColumns[0], 'relationFields' => $columns[0]); } } } } } } else { foreach ($db->listTables($schema) as $name) { if ($defineRelations) { $hasMany[$name] = array(); $belongsTo[$name] = array(); $foreignKeys[$name] = array(); } } } foreach ($db->listTables($schema) as $name) { $className = $this->options->contains('abstract') ? 'Abstract' : ''; $className .= Utils::camelize($name); if (!file_exists($modelPath . $className . '.php') || $forceProcess) { if (isset($hasMany[$name])) { $hasManyModel = $hasMany[$name]; } else { $hasManyModel = array(); } if (isset($belongsTo[$name])) { $belongsToModel = $belongsTo[$name]; } else { $belongsToModel = array(); } if (isset($foreignKeys[$name])) { $foreignKeysModel = $foreignKeys[$name]; } else { $foreignKeysModel = array(); } $modelBuilder = new Model(array('name' => $name, 'schema' => $schema, 'extends' => $this->options->get('extends'), 'namespace' => $this->options->get('namespace'), 'force' => $forceProcess, 'hasMany' => $hasManyModel, 'belongsTo' => $belongsToModel, 'foreignKeys' => $foreignKeysModel, 'genSettersGetters' => $genSettersGetters, 'directory' => $this->options->get('directory'), 'modelsDir' => $this->options->get('modelsDir'), 'mapColumn' => $mapColumn, 'abstract' => $this->options->get('abstract'))); $modelBuilder->build(); } else { if ($this->isConsole()) { print Color::info(sprintf('Skipping model "%s" because it already exist', Utils::camelize($name))); } else { $this->exist[] = $name; } } } }
/** * @param \Phalcon\Db\ColumnInterface[] $fields * @param bool $camelize * @return string */ public function getColumnMap($fields, $camelize = false) { $template = <<<EOD /** * Independent Column Mapping. * Keys are the real names in the table and the values their names in the application * * @return array */ public function columnMap() { return array( %s ); } EOD; $contents = array(); foreach ($fields as $field) { $name = $field->getName(); $contents[] = sprintf('\'%s\' => \'%s\'', $name, $camelize ? Utils::lowerCamelize($name) : $name); } return PHP_EOL . sprintf($template, join(",\n ", $contents)) . PHP_EOL; }
/** * @return string * @throws \Phalcon\Builder\BuilderException */ public function build() { // load root path if ($this->options->contains('directory')) { $this->path->setRootPath($this->options->get('directory')); } // load module path if ($this->options->contains('module')) { // get module dir $config = $this->getConfig(); if (!isset($config->application->modulesDir)) { if (!file_exists($config->application->modulesDir)) { mkdir($config->application->modulesDir); } throw new BuilderException('Please specify a modules directory.'); } $_rootPath = rtrim($config->application->modulesDir, '\\/') . DIRECTORY_SEPARATOR; $module = $this->options->get('module'); if (!file_exists($_rootPath . $module)) { throw new BuilderException('module not frond.'); } $this->path->setRootPath($_rootPath . $module . DIRECTORY_SEPARATOR); } $namespace = 'Application\\' . $this->options->get('module') . '\\Controllers'; if (!$this->options->contains('namespace') && $this->options->contains('module') && $this->checkNamespace($namespace)) { // if namespace is empty and has module $namespace = 'namespace ' . $namespace . ';' . PHP_EOL . PHP_EOL; } elseif ($this->options->contains('namespace') && $this->checkNamespace($this->options->get('namespace'))) { $namespace = 'namespace ' . $this->options->get('namespace') . ';' . PHP_EOL . PHP_EOL; } else { $namespace = ''; } $baseClass = $this->options->get('baseClass', '\\Phalcon\\Mvc\\Controller'); $config = $this->getConfig(); if (!isset($config->application->controllersDir)) { throw new BuilderException('Please specify a controller directory.'); } $controllersDir = $config->application->controllersDir; if (!$this->options->contains('name')) { throw new BuilderException('The controller name is required.'); } $name = str_replace(' ', '_', $this->options->get('name')); $className = Utils::camelize($name); // Oops! We are in APP_PATH and try to get controllersDir from outside from project dir if ($this->isConsole() && substr($controllersDir, 0, 3) === '../') { $controllersDir = ltrim($controllersDir, './'); } $controllerPath = rtrim($controllersDir, '\\/') . DIRECTORY_SEPARATOR . $className . "Controller.php"; $code = "<?php\n\n" . $namespace . "class " . $className . "Controller extends " . $baseClass . "\n{\n\n\tpublic function indexAction()\n\t{\n\n\t}\n\n}\n\n"; $code = str_replace("\t", " ", $code); if (file_exists($controllerPath) && !$this->options->contains('force')) { throw new BuilderException(sprintf('The Controller %s already exists.', $name)); } $controller = new SplFileObject($controllerPath, 'w'); if (!$controller->fwrite($code)) { throw new BuilderException(sprintf('Unable to write to %s. Check write-access of a file.', $controller->getRealPath())); } if ($this->isConsole()) { $this->_notifySuccess(sprintf('Controller "%s" was successfully created.', $name)); echo $controller->getRealPath(), PHP_EOL; } return $className . 'Controller.php'; }