/** * Generate view */ public function build() { $action = Text::uncamelize($this->_options['action']); $viewName = explode('-', str_replace('_', '-', Text::uncamelize($this->_options['name']))); if (count($viewName) > 1) { array_pop($viewName); } $viewName = implode('-', $viewName); $viewDir = $this->_options['directory'] . DIRECTORY_SEPARATOR . $viewName; $viewPath = $viewDir . DIRECTORY_SEPARATOR . $action . '.volt'; $code = "<?php\n" . Tools::getCopyright() . "\n?>\n"; $code = str_replace("\t", " ", $code); if (!file_exists($viewPath) || $this->_options['force'] == true) { if (!is_dir($viewDir)) { mkdir($viewDir, 0777, true); chmod($viewDir, 0777); } if (!@file_put_contents($viewPath, $code)) { throw new \Exception("Unable to write to '{$viewPath}'"); } chmod($viewPath, 0777); } else { throw new \Exception("The View '{$action}' already exists"); } return $viewName; }
/** * Build the controller * * @return string * @throws \Exception */ public function build() { if ($this->_options['namespace'] != 'None') { $namespace = 'namespace ' . $this->_options['namespace'] . ';' . PHP_EOL . PHP_EOL; } else { $namespace = ''; } $controllerPath = $this->_options['directory'] . DIRECTORY_SEPARATOR . $this->_options['name'] . ".php"; $base = explode('\\', $this->_options['baseClass']); $baseClass = end($base); $useClass = 'use ' . $this->_options['baseClass'] . ';' . PHP_EOL . PHP_EOL; $code = "<?php\n" . Tools::getCopyright() . "\n\n" . $namespace . $useClass . "/**\n * Class " . $this->_options['name'] . "\n * @package " . $this->_options['namespace'] . "\n */\nclass " . $this->_options['name'] . " extends {$baseClass}\n{\n public function indexAction()\n {\n\n\t}\n}"; $code = str_replace("\t", " ", $code); if (!file_exists($controllerPath) || $this->_options['force'] == true) { if (!is_dir($this->_options['directory'])) { @mkdir($this->_options['directory'], 0777, true); @chmod($this->_options['directory'], 0777); } if (!@file_put_contents($controllerPath, $code)) { throw new \Exception("Unable to write to '{$controllerPath}'"); } @chmod($controllerPath, 0777); } else { throw new \Exception("The Controller '" . $this->_options['name'] . "' already exists"); } return $this->_options['name'] . '.php'; }
/** * Generate module file * @throws \Exception */ private function _createModule() { $code = "<?php\n" . Tools::getCopyright() . PHP_EOL . PHP_EOL . 'namespace ' . $this->_options['namespace'] . ';' . PHP_EOL . PHP_EOL; if (Tools::fullVersion()) { $code .= 'use Phalcon\\DiInterface;' . PHP_EOL . 'use Phalcon\\Loader;' . PHP_EOL . 'use Phalcon\\Mvc\\View;' . PHP_EOL . 'use Phalcon\\Mvc\\Dispatcher;' . PHP_EOL . 'use Phalcon\\Mvc\\ModuleDefinitionInterface;'; } $baseModule = Tools::getBaseModule(); if (!empty($baseModule)) { $base = explode('\\', Tools::getBaseModule()); $baseClass = end($base); $useClass = PHP_EOL . 'use ' . Tools::getBaseModule() . ';'; $code .= $useClass; } $code .= PHP_EOL . PHP_EOL . '/** * Class Module * @package ' . $this->_options['namespace'] . ' */ class Module'; if (!empty($baseModule)) { $code .= " extends {$baseClass}"; } if (Tools::fullVersion()) { $code .= " implements ModuleDefinitionInterface\n{\n\t/**\n * Register a specific autoloader for the module\n * @param \\Phalcon\\DiInterface \$di\n */\n public function registerAutoloaders(DiInterface \$di = null)\n {\n \$loader = new Loader();\n \$loader->registerNamespaces(\n array(" . PHP_EOL . "\t\t\t\t'" . $this->_options['namespace'] . '\\' . Tools::getControllersDir() . "' => __DIR__ . '/" . Tools::getControllersDir() . "'," . PHP_EOL . "\t\t\t\t'" . $this->_options['namespace'] . '\\' . Tools::getModelsDir() . "' => __DIR__ . '/" . Tools::getModelsDir() . "'" . PHP_EOL . "\t\t\t)\n );\n \$loader->register();\n }\n\n /**\n * Register specific services for the module\n * @param \\Phalcon\\DiInterface \$di\n */\n public function registerServices(DiInterface \$di)\n {\n //Registering a dispatcher\n \$di->set('dispatcher', function() {\n \$dispatcher = new Dispatcher();\n \$dispatcher->setDefaultNamespace('" . $this->_options['namespace'] . "');\n return \$dispatcher;\n });\n\n //Registering the view component\n \$di->set('view', function() {\n \$view = new View();\n \$view->setViewsDir(__DIR__ . '/" . Tools::getViewsDir() . "');\n return \$view;\n });\n }\n}"; } else { $code .= " {" . PHP_EOL . PHP_EOL . "}"; } $code = str_replace("\t", " ", $code); $modulePath = $this->_options['directory'] . DIRECTORY_SEPARATOR . 'Module.php'; if (!file_exists($modulePath) || $this->_options['force'] == true) { if (!@file_put_contents($modulePath, $code)) { throw new \Exception("Unable to write to '{$modulePath}'"); } @chmod($modulePath, 0777); } else { throw new \Exception("Module.php file already exists"); } }
/** * Generate migrations * * @param array $options * @throws \Exception */ public static function generate(array $options) { $tableName = $options['tableName']; $exportData = $options['exportData']; $migrationsDir = $options['migrationsDir']; $originalVersion = $options['originalVersion']; $force = $options['force']; $config = $options['config']; if ($migrationsDir && !file_exists($migrationsDir)) { mkdir($migrationsDir, 0777, true); } if ($originalVersion) { if (!preg_match('/[a-z0-9](\\.[a-z0-9]+)*/', $originalVersion, $matches)) { throw new \Exception('Version ' . $originalVersion . ' is invalid'); } $originalVersion = $matches[0]; $version = new VersionItem($originalVersion, 3); if (file_exists($migrationsDir . '/' . $version) && !$force) { throw new \Exception('Version ' . $version . ' is already generated'); } } else { $versions = array(); $iterator = new \DirectoryIterator($migrationsDir); foreach ($iterator as $fileInfo) { if ($fileInfo->isDir()) { if (preg_match('/[a-z0-9](\\.[a-z0-9]+)+/', $fileInfo->getFilename(), $matches)) { $versions[] = new VersionItem($matches[0], 3); } } } if (count($versions) == 0) { $version = new VersionItem('1.0.0'); } else { $version = VersionItem::maximum($versions); $version = $version->addMinor(1); } } if (!file_exists($migrationsDir . '/' . $version)) { if (!@mkdir($migrationsDir . '/' . $version)) { throw new \Exception("Cannot create migration version directory"); } @chmod($migrationsDir . '/' . $version, 0777); } if (isset($config->database)) { ModelMigration::setup($config->database); } else { throw new \Exception("Cannot load database configuration"); } ModelMigration::setSkipAutoIncrement($options['no-ai']); ModelMigration::setMigrationPath($migrationsDir . '/' . $version); if ($tableName == 'all') { $migrations = ModelMigration::generateAll($version, $exportData); foreach ($migrations as $tableName => $migration) { file_put_contents($migrationsDir . '/' . $version . '/' . $tableName . '.php', '<?php' . PHP_EOL . Tools::getCopyright() . PHP_EOL . PHP_EOL . $migration); @chmod($migrationsDir . '/' . $version . '/' . $tableName . '.php', 0777); } } else { $migration = ModelMigration::generate($version, $tableName, $exportData); file_put_contents($migrationsDir . '/' . $version . '/' . $tableName . '.php', '<?php ' . PHP_EOL . Tools::getCopyright() . PHP_EOL . PHP_EOL . $migration); @chmod($migrationsDir . '/' . $version . '/' . $tableName . '.php', 0777); } }
/** * Generate controller using scaffold * * @param array $options */ private function _makeController($options) { $controllerPath = $options['controllersDir'] . $options['className'] . 'Controller.php'; if (!is_dir($options['controllersDir'])) { if (!mkdir($options['controllersDir'])) { return; } @chmod($options['controllersDir'], 0777); } if (file_exists($controllerPath)) { if (!$options['force']) { return; } } $path = $options['templatePath'] . '/scaffold/no-forms/Controller.php'; $code = file_get_contents($path); $code = str_replace('$modelClass$', $options['modelClass'], $code); if (Tools::getCopyright() == null) { $code = str_replace('$copyright$', '', $code); } else { $code = str_replace('$copyright$', PHP_EOL . Tools::getCopyright() . PHP_EOL, $code); } if (isset($options['controllersNamespace']) === true) { $code = str_replace('$namespace$', 'namespace ' . $options['controllersNamespace'] . ';', $code); } else { $code = str_replace('$namespace$', ' ', $code); } $code = str_replace('$singularVar$', '$' . $options['singular'], $code); $code = str_replace('$singular$', $options['singular'], $code); $code = str_replace('$pluralVar$', '$' . $options['plural'], $code); $code = str_replace('$plural$', $options['plural'], $code); $code = str_replace('$className$', $options['className'], $code); $code = str_replace('$package$', $options['controllersNamespace'], $code); $code = str_replace('$controllerClass$', Tools::getBaseController()[0], $code); $explodeController = explode('\\', Tools::getBaseController()[0]); $code = str_replace('$controllerName$', array_pop($explodeController), $code); $code = str_replace('$assignInputFromRequestCreate$', $this->_captureFilterInput($options['singular'], $options['dataTypes'], $options['genSettersGetters'], $options['identityField']), $code); $code = str_replace('$assignInputFromRequestUpdate$', $this->_captureFilterInput($options['singular'], $options['dataTypes'], $options['genSettersGetters'], $options['identityField']), $code); $code = str_replace('$assignTagDefaults$', $this->_assignTagDefaults($options['singular'], $options['dataTypes'], $options['genSettersGetters']), $code); $code = str_replace('$pkVar$', '$' . $options['attributes'][0], $code); $code = str_replace('$pkFind$', Text::camelize($options['attributes'][0]), $code); $code = str_replace('$pk$', $options['attributes'][0], $code); $code = str_replace("\t", " ", $code); file_put_contents($controllerPath, $code); @chmod($controllerPath, 0777); }
public function build() { $getSource = "\n public function getSource()\n {\n return '%s';\n }\n"; $templateThis = " \$this->%s(%s);" . PHP_EOL; $templateRelation = " \$this->%s('%s', '%s', '%s', %s);" . PHP_EOL; $templateSetter = "\n /**\n * Method to set the value of field %s\n *\n * @param %s \$%s\n * @return \$this\n */\n public function set%s(\$%s)\n {\n \$this->%s = \$%s;\n\n return \$this;\n }\n"; $templateValidateInclusion = "\n \$this->validate(\n new InclusionIn(\n array(\n 'field' => '%s',\n 'domain' => array(%s),\n 'required' => true,\n )\n )\n );"; $templateValidateEmail = "\n \$this->validate(\n new Email(\n array(\n 'field' => '%s',\n 'required' => true,\n )\n )\n );"; $templateValidationFailed = "\n if (\$this->validationHasFailed() == true) {\n return false;\n }"; $templateAttributes = "\n /**\n * @var %s\n */\n %s \$%s;\n"; $templateGetterMap = "\n /**\n * Returns the value of field %s\n *\n * @return %s\n */\n public function get%s()\n {\n if (\$this->%s) {\n return new %s(\$this->%s);\n } else {\n return null;\n }\n }\n"; $templateGetter = "\n /**\n * Returns the value of field %s\n *\n * @return %s\n */\n public function get%s()\n {\n return \$this->%s;\n }\n"; $templateValidations = "\n /**\n * Validations and business logic\n */\n public function validation()\n {\n%s\n }\n"; $templateInitialize = "\n /**\n * Initialize method for model.\n */\n public function initialize()\n {\n%s\n }\n"; $templateFind = "\n /**\n * @return %s[]\n */\n public static function find(\$parameters = array())\n {\n return parent::find(\$parameters);\n }\n\n /**\n * @return %s\n */\n public static function findFirst(\$parameters = array())\n {\n return parent::findFirst(\$parameters);\n }\n"; $templateUse = 'use %s;'; $templateUseAs = 'use %s as %s;'; $templateCode = "<?php\n%s%s%s%s\nclass %s extends %s\n{\n%s\n}\n"; $methodRawCode = array(); $modelPath = $this->_options['directory'] . DIRECTORY_SEPARATOR . $this->_options['name'] . '.php'; if (file_exists($modelPath)) { if (!$this->_options['force']) { throw new \Exception("The model file '" . $this->_options['name'] . ".php' already exists in " . $this->_options['directory']); } } if (Tools::getDb()) { $dbConfig = Tools::getDb(); } if (!isset($dbConfig->adapter)) { throw new \Exception("Adapter was not found in the config. " . "Please specify a config variable [database][adapter]"); } if (isset($this->_options['namespace'])) { $namespace = PHP_EOL . PHP_EOL . 'namespace ' . $this->_options['namespace'] . ';' . PHP_EOL . PHP_EOL; $methodRawCode[] = sprintf($getSource, $this->_options['tableName']); } else { $namespace = ''; } $useSettersGetters = $this->_options['genSettersGetters']; if (isset($this->_options['genDocMethods'])) { $genDocMethods = $this->_options['genDocMethods']; } else { $genDocMethods = false; } $this->isSupportedAdapter($dbConfig->adapter); if (isset($dbConfig->adapter)) { $adapter = $dbConfig->adapter; } else { $adapter = 'Mysql'; } $configArray = $dbConfig->toArray(); // An array for use statements $uses = array(sprintf($templateUse, $this->_options['baseClass'])); $adapterName = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $adapter; unset($configArray['adapter']); $db = new $adapterName($configArray); $initialize = array(); if (isset($this->_options['schema'])) { if ($this->_options['schema'] != $dbConfig->dbname) { $initialize[] = sprintf($templateThis, 'setSchema', '"' . $this->_options['schema'] . '"'); } $schema = $this->_options['schema']; } elseif ($adapter == 'Postgresql') { $schema = 'public'; $initialize[] = sprintf($templateThis, 'setSchema', '"' . $schema . '"'); } else { $schema = $dbConfig->dbname; } if ($this->_options['name'] != $this->_options['tableName']) { $initialize[] = sprintf($templateThis, 'setSource', '\'' . $this->_options['tableName'] . '\''); } $table = $this->_options['tableName']; if ($db->tableExists($table, $schema)) { $fields = $db->describeColumns($table, $schema); } else { throw new \Exception('Table "' . $table . '" does not exist'); } foreach ($db->listTables() as $tableName) { foreach ($db->describeReferences($tableName) as $reference) { if ($reference->getReferencedTable() == $this->_options['tableName']) { if (isset($this->_options['namespace'])) { $entityNamespace = "{$this->_options['namespace']}\\"; } else { $entityNamespace = ''; } $initialize[] = sprintf($templateRelation, 'hasMany', $reference->getReferencedColumns()[0], $entityNamespace . ucfirst($tableName), $reference->getColumns()[0], "array('alias' => '" . ucfirst($tableName) . "')"); } } } foreach ($db->describeReferences($this->_options['tableName']) as $reference) { if (isset($this->_options['namespace'])) { $entityNamespace = "{$this->_options['namespace']}\\"; } else { $entityNamespace = ''; } $initialize[] = sprintf($templateRelation, 'belongsTo', $reference->getColumns()[0], $entityNamespace . ucfirst($reference->getReferencedTable()), $reference->getReferencedColumns()[0], "array('alias' => '" . ucfirst($reference->getReferencedTable()) . "')"); } if (isset($this->_options['hasMany'])) { if (count($this->_options['hasMany'])) { foreach ($this->_options['hasMany'] as $relation) { if (is_string($relation['fields'])) { $entityName = $relation['camelizedName']; if (isset($this->_options['namespace'])) { $entityNamespace = "{$this->_options['namespace']}\\"; $relation['options']['alias'] = $entityName; } else { $entityNamespace = ''; } $initialize[] = sprintf($templateRelation, 'hasMany', $relation['fields'], $entityNamespace . $entityName, $relation['relationFields'], $this->_buildRelationOptions(isset($relation['options']) ? $relation["options"] : NULL)); } } } } if (isset($this->_options['belongsTo'])) { if (count($this->_options['belongsTo'])) { foreach ($this->_options['belongsTo'] as $relation) { if (is_string($relation['fields'])) { $entityName = $relation['referencedModel']; if (isset($this->_options['namespace'])) { $entityNamespace = "{$this->_options['namespace']}\\"; $relation['options']['alias'] = $entityName; } else { $entityNamespace = ''; } $initialize[] = sprintf($templateRelation, 'belongsTo', $relation['fields'], $entityNamespace . $entityName, $relation['relationFields'], $this->_buildRelationOptions(isset($relation['options']) ? $relation["options"] : NULL)); } } } } $alreadyInitialized = false; $alreadyValidations = false; if (file_exists($modelPath)) { try { $possibleMethods = array(); if ($useSettersGetters) { foreach ($fields as $field) { $methodName = Text::camelize($field->getName()); $possibleMethods['set' . $methodName] = true; $possibleMethods['get' . $methodName] = true; } } require_once $modelPath; $linesCode = file($modelPath); $fullClassName = $this->_options['namespace']; $reflection = new \ReflectionClass($fullClassName); foreach ($reflection->getMethods() as $method) { if ($method->getDeclaringClass()->getName() == $fullClassName) { $methodName = $method->getName(); if (!isset($possibleMethods[$methodName])) { $methodRawCode[$methodName] = join('', array_slice($linesCode, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1)); } else { continue; } if ($methodName == 'initialize') { $alreadyInitialized = true; } else { if ($methodName == 'validation') { $alreadyValidations = true; } } } } } 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[] = sprintf($templateValidateInclusion, $field->getName(), $varItems); } } if ($field->getName() == 'email') { $validations[] = sprintf($templateValidateEmail, $field->getName()); $uses[] = sprintf($templateUse, '\\Phalcon\\Mvc\\Model\\Validator\\Email'); } } if (count($validations)) { $validations[] = $templateValidationFailed; } /** * Check if there have been any excluded fields */ $exclude = array(); if (isset($this->_options['excludeFields'])) { if (!empty($this->_options['excludeFields'])) { $keys = explode(',', $this->_options['excludeFields']); if (count($keys) > 0) { foreach ($keys as $key) { $exclude[trim($key)] = ''; } } } } $attributes = array(); $setters = array(); $getters = array(); foreach ($fields as $field) { $type = $this->getPHPType($field->getType()); if ($useSettersGetters) { if (!array_key_exists(strtolower($field->getName()), $exclude)) { $attributes[] = sprintf($templateAttributes, $type, 'protected', $field->getName()); $setterName = Text::camelize($field->getName()); $setters[] = sprintf($templateSetter, $field->getName(), $type, $field->getName(), $setterName, $field->getName(), $field->getName(), $field->getName()); if (isset($this->_typeMap[$type])) { $getters[] = sprintf($templateGetterMap, $field->getName(), $type, $setterName, $field->getName(), $this->_typeMap[$type], $field->getName()); } else { $getters[] = sprintf($templateGetter, $field->getName(), $type, $setterName, $field->getName()); } } } else { $attributes[] = sprintf($templateAttributes, $type, 'public', $field->getName()); } } if ($alreadyValidations == false) { if (count($validations) > 0) { $validationsCode = sprintf($templateValidations, join('', $validations)); } else { $validationsCode = ''; } } else { $validationsCode = ''; } if ($alreadyInitialized == false) { if (count($initialize) > 0) { $initCode = sprintf($templateInitialize, rtrim(join('', $initialize))); } else { $initCode = ''; } } else { $initCode = ''; } $content = join('', $attributes); if ($useSettersGetters) { $content .= join('', $setters) . join('', $getters); } $content .= $validationsCode . $initCode; foreach ($methodRawCode as $methodCode) { $content .= $methodCode; } if ($genDocMethods) { $content .= sprintf($templateFind, $this->_options['name'], $this->_options['name']); } if (isset($this->_options['mapColumn'])) { $content .= $this->_genColumnMapCode($fields); } $str_use = implode(PHP_EOL, $uses) . PHP_EOL . PHP_EOL; $str_doc = '/** * Class ' . $this->_options['name'] . ' * @package ' . $this->_options['namespace'] . ' */'; $base = explode('\\', $this->_options['baseClass']); $baseClass = end($base); $code = sprintf($templateCode, Tools::getCopyright(), $namespace, $str_use, $str_doc, $this->_options['name'], $baseClass, $content); if (!@is_dir($this->_options['directory'])) { @mkdir($this->_options['directory']); @chmod($this->_options['directory'], 0777); } if (!@file_put_contents($modelPath, $code)) { throw new \Exception("Unable to write to '{$modelPath}'"); } @chmod($modelPath, 0777); }