public function build() { $path = ''; if (isset($this->_options['directory'])) { if ($this->_options['directory']) { $path = $this->_options['directory'] . '/'; } } if (isset($this->_options['templatePath'])) { $templatePath = $this->_options['templatePath']; } else { $templatePath = str_replace('scripts/' . str_replace('\\', DIRECTORY_SEPARATOR, __CLASS__) . '.php', '', __FILE__) . 'templates'; } if (file_exists($path . '.phalcon')) { throw new BuilderException("Projects cannot be created inside Phalcon projects"); } if (isset($this->_options['type'])) { $type = $this->_options['type']; if (!isset($this->_types[$type])) { $keys = array_keys($this->_types); $keys = implode(" , ", $keys); throw new BuilderException('Type "' . $type . '" is not a valid type. Choose among [' . $keys . '] '); } } else { $type = 'simple'; } $name = null; if (isset($this->_options['name'])) { if ($this->_options['name']) { $name = $this->_options['name']; $path .= $this->_options['name'] . '/'; if (file_exists($path)) { throw new BuilderException("Directory " . $path . " already exists"); } mkdir($path); } } if (!is_writable($path)) { throw new BuilderException("Directory " . $path . " is not writable"); } $builderClass = $this->_types[$type]; $builder = new $builderClass(); $success = $builder->build($name, $path, $templatePath, $this->_options); if ($success === true) { print Color::success('Project "' . $name . '" was successfully created.') . PHP_EOL; } return $success; }
/** * {@inheritdoc} * * @param array $parameters * @return mixed * @throws CommandsException */ public function run(array $parameters) { $action = $this->getOption(array('action', 1)); $directory = './'; if ($action == 'enable') { if (file_exists($directory . 'public/webtools.php')) { throw new CommandsException('Webtools are already enabled!'); } Tools::install($directory); echo Color::success('Webtools successfully enabled!'); } elseif ($action == 'disable') { if (!file_exists($directory . 'public/webtools.php')) { throw new CommandsException('Webtools are already disabled!'); } Tools::uninstall($directory); echo Color::success('Webtools successfully disabled!'); } else { throw new CommandsException('Invalid action!'); } }
public function run($parameters) { $action = $this->getOption(array('action', 1)); $directory = $this->getOption(array('directory')); if (!$directory) { $directory = __DIR__ . '/../../../../'; } if ($action == 'enable') { Tools::install($directory); } else { if ($action == 'disable') { Tools::install($directory); } else { throw new \Exception("Invalid action"); } } if ($action == 'enable') { print Color::success('Webtools successfully enabled') . PHP_EOL; } else { if ($action == 'disable') { print Color::success('Webtools successfully disabled') . PHP_EOL; } } }
public function build($name, $path, $templatePath, $options) { $this->buildDirectories($this->_dirs, $path); //Disable ini config // if (isset($options['useConfigIni'])) // $useIniConfig = $options['useConfigIni']; // else $useIniConfig = false; if ($useIniConfig) { $this->createConfig($path, $templatePath, 'ini'); } else { $this->createConfig($path, $templatePath, 'php'); } $this->createBootstrapFiles($path, $templatePath, $useIniConfig); $this->createDefaultTasks($path, $templatePath); $this->createLauncher($name, $path, $templatePath); $pathSymLink = realpath($path . $name); print Color::success("You can create a symlink to {$pathSymLink} to invoke the application") . PHP_EOL; return true; }
/** * Run migrations * * @param array $options * * @throws Exception * @throws ModelException * @throws ScriptException */ public static function run(array $options) { $path = $options['directory']; $migrationsDir = $options['migrationsDir']; if (!file_exists($migrationsDir)) { throw new ModelException('Migrations directory could not found.'); } $config = $options['config']; if (!$config instanceof Config) { throw new ModelException('Internal error. Config should be instance of \\Phalcon\\Config'); } $finalVersion = null; if (isset($options['version']) && $options['version'] !== null) { $finalVersion = new VersionItem($options['version']); } $tableName = 'all'; if (isset($options['tableName'])) { $tableName = $options['tableName']; } // read all versions $versions = array(); $iterator = new \DirectoryIterator($migrationsDir); foreach ($iterator as $fileinfo) { if ($fileinfo->isDir() && preg_match('/[a-z0-9](\\.[a-z0-9]+)+/', $fileinfo->getFilename(), $matches)) { $versions[] = new VersionItem($matches[0], 3); } } if (count($versions) == 0) { throw new ModelException('Migrations were not found at ' . $migrationsDir); } // set default final version if ($finalVersion === null) { $finalVersion = VersionItem::maximum($versions); } // read current version if (is_file($path . '.phalcon')) { unlink($path . '.phalcon'); mkdir($path . '.phalcon'); } $migrationFid = $path . '.phalcon/migration-version'; $initialVersion = new VersionItem(file_exists($migrationFid) ? file_get_contents($migrationFid) : null); if ($initialVersion->getStamp() == $finalVersion->getStamp()) { return; // nothing to do } // init ModelMigration if (!isset($config->database)) { throw new ScriptException('Cannot load database configuration'); } ModelMigration::setup($config->database); ModelMigration::setMigrationPath($migrationsDir); // run migration $versionsBetween = VersionItem::between($initialVersion, $finalVersion, $versions); foreach ($versionsBetween as $k => $version) { /** @var \Phalcon\Version\Item $version */ if ($tableName == 'all') { $iterator = new \DirectoryIterator($migrationsDir . '/' . $version); foreach ($iterator as $fileinfo) { if (!$fileinfo->isFile() || !preg_match('/\\.php$/i', $fileinfo->getFilename())) { continue; } ModelMigration::migrate($initialVersion, $version, $fileinfo->getBasename('.php')); } } else { ModelMigration::migrate($initialVersion, $version, $tableName); } file_put_contents($migrationFid, (string) $version); print Color::success('Version ' . $version . ' was successfully migrated'); $initialVersion = $version; } }
/** * Run migrations * * @param array $options * * @throws Exception * @throws ModelException * @throws ScriptException */ public static function run(array $options) { $path = $options['directory']; $migrationsDir = $options['migrationsDir']; if (!file_exists($migrationsDir)) { throw new ModelException('Migrations directory could not found.'); } self::$_config = $options['config']; if (!self::$_config instanceof Config) { throw new ModelException('Internal error. Config should be instance of \\Phalcon\\Config'); } $finalVersion = null; if (isset($options['version']) && $options['version'] !== null) { $finalVersion = new VersionItem($options['version']); } $tableName = 'all'; if (isset($options['tableName'])) { $tableName = $options['tableName']; } $versions = ModelMigration::scanForVersions($migrationsDir); if (!count($versions)) { throw new ModelException("Migrations were not found at {$migrationsDir}"); } // set default final version if (!$finalVersion) { $finalVersion = VersionItem::maximum($versions); } // read current version if (is_file($path . '.phalcon')) { unlink($path . '.phalcon'); mkdir($path . '.phalcon'); chmod($path . '.phalcon', 0775); } self::$_migrationFid = $path . '.phalcon/migration-version'; // init ModelMigration if (!is_null(self::$_config->get('database'))) { throw new ScriptException('Cannot load database configuration'); } ModelMigration::setup(self::$_config->get('database')); ModelMigration::setMigrationPath($migrationsDir); $initialVersion = self::getCurrentVersion(); if ($initialVersion->getStamp() == $finalVersion->getStamp()) { return; // nothing to do } $direction = ModelMigration::DIRECTION_FORWARD; if ($finalVersion->getStamp() < $initialVersion->getStamp()) { $direction = ModelMigration::DIRECTION_BACK; } // run migration $lastGoodVersion = $initialVersion; $versionsBetween = VersionItem::between($initialVersion, $finalVersion, $versions); foreach ($versionsBetween as $version) { if ($tableName == 'all') { $iterator = new DirectoryIterator($migrationsDir . DIRECTORY_SEPARATOR . $version); foreach ($iterator as $fileInfo) { if (!$fileInfo->isFile() || 0 !== strcasecmp($fileInfo->getExtension(), 'php')) { continue; } ModelMigration::migrate($initialVersion, $version, $fileInfo->getBasename('.php'), $direction); } } else { ModelMigration::migrate($initialVersion, $version, $tableName, $direction); } self::setCurrentVersion((string) $lastGoodVersion, (string) $version); $lastGoodVersion = $version; print Color::success('Version ' . $version . ' was successfully migrated'); $initialVersion = $version; } }
/** * Shows a success notification * * @param string $message */ protected function _notifySuccess($message) { print Color::success($message); }
/** * Run migrations * * @param array $options * * @throws Exception * @throws ModelException * @throws ScriptException * @throws \Exception */ public static function run(array $options) { $path = $options['directory']; $migrationsDir = $options['migrationsDir']; $config = $options['config']; $version = null; if (isset($options['version']) && $options['version'] !== null) { $version = new VersionItem($options['version']); } if (isset($options['tableName'])) { $tableName = $options['tableName']; } else { $tableName = 'all'; } if (!file_exists($migrationsDir)) { throw new ModelException('Migrations directory could not found'); } $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) { throw new ModelException('Migrations were not found at ' . $migrationsDir); } else { if ($version === null) { $version = VersionItem::maximum($versions); } } if (is_file($path . '.phalcon')) { unlink($path . '.phalcon'); mkdir($path . '.phalcon'); } $migrationFid = $path . '.phalcon/migration-version'; if (file_exists($migrationFid)) { $fromVersion = trim(file_get_contents($migrationFid)); } else { $fromVersion = null; } if (isset($config->database)) { ModelMigration::setup($config->database); } else { throw new \Exception("Cannot load database configuration"); } ModelMigration::setMigrationPath($migrationsDir . '/' . $version . '/'); $versionsBetween = VersionItem::between($fromVersion, $version, $versions); // get rid of the current version, we don't want migrations to run for our // existing version. if (isset($versionsBetween[0]) && (string) $versionsBetween[0] == $fromVersion) { unset($versionsBetween[0]); } foreach ($versionsBetween as $version) { if ($tableName == 'all') { $iterator = new \DirectoryIterator($migrationsDir . '/' . $version); foreach ($iterator as $fileinfo) { if ($fileinfo->isFile()) { if (preg_match('/\\.php$/', $fileinfo->getFilename())) { ModelMigration::migrateFile((string) $version, $migrationsDir . '/' . $version . '/' . $fileinfo->getFilename()); } } } } else { $migrationPath = $migrationsDir . '/' . $version . '/' . $tableName . '.php'; if (!file_exists($migrationPath)) { throw new ScriptException('Migration class was not found ' . $migrationPath); } ModelMigration::migrateFile((string) $version, $migrationPath); } print Color::success('Version ' . $version . ' was successfully migrated') . PHP_EOL; } file_put_contents($migrationFid, (string) $version); }
public function build() { $getSource = "\n public function getSource()\n {\n return '%s';\n }\n"; $templateThis = "\t\t\$this->%s(%s);\n"; $templateRelation = "\t\t\$this->%s(\"%s\", \"%s\", \"%s\");\n"; $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 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 *\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"; $templateCode = "<?php\n%s\n%s\nclass %s extends %s\n{\n%s\n}\n"; if (!$this->_options['name']) { throw new BuilderException("You must specify the table name"); } $path = ''; if (isset($this->_options['directory'])) { if ($this->_options['directory']) { $path = $this->_options['directory'] . '/'; } } $config = $this->_getConfig($path); if (!isset($this->_options['modelsDir'])) { if (!isset($config->application->modelsDir)) { throw new BuilderException("Builder doesn't knows where is the models directory"); } $modelsDir = $config->application->modelsDir; } else { $modelsDir = $this->_options['modelsDir']; } if ($this->isAbsolutePath($modelsDir) == false) { $modelPath = $path . "public" . DIRECTORY_SEPARATOR . $modelsDir; } else { $modelPath = $modelsDir; } $methodRawCode = array(); $className = $this->_options['className']; $modelPath .= $className . '.php'; if (file_exists($modelPath)) { if (!$this->_options['force']) { throw new BuilderException("The model file '" . $className . ".php' already exists in models dir"); } } 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]"); } if (isset($this->_options['namespace'])) { $namespace = 'namespace ' . $this->_options['namespace'] . ';' . PHP_EOL . PHP_EOL; $methodRawCode[] = sprintf($getSource, $this->_options['name']); } else { $namespace = ''; } $useSettersGetters = $this->_options['genSettersGetters']; if (isset($this->_options['genDocMethods'])) { $genDocMethods = $this->_options['genDocMethods']; } else { $genDocMethods = false; } $adapter = $config->database->adapter; $this->isSupportedAdapter($adapter); if (isset($config->database->adapter)) { $adapter = $config->database->adapter; } else { $adapter = 'Mysql'; } if (is_object($config->database)) { $configArray = $config->database->toArray(); } else { $configArray = $config->database; } $adapterName = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter; unset($configArray['adapter']); $db = new $adapterName($configArray); $initialize = array(); if (isset($this->_options['schema'])) { if ($this->_options['schema'] != $config->database->dbname) { $initialize[] = sprintf($templateThis, 'setSchema', '"' . $this->_options['schema'] . '"'); } $schema = $this->_options['schema']; } elseif ($adapter == 'Postgresql') { $schema = 'public'; $initialize[] = sprintf($templateThis, 'setSchema', '"' . $this->_options['schema'] . '"'); } else { $schema = $config->database->dbname; } if ($this->_options['fileName'] != $this->_options['name']) { $initialize[] = sprintf($templateThis, 'setSource', '\'' . $this->_options['name'] . '\''); } $table = $this->_options['name']; if ($db->tableExists($table, $schema)) { $fields = $db->describeColumns($table, $schema); } else { throw new BuilderException('Table "' . $table . '" does not exists'); } if (isset($this->_options['hasMany'])) { if (count($this->_options['hasMany'])) { foreach ($this->_options['hasMany'] as $relation) { if (is_string($relation['fields'])) { $entityName = $relation['camelizedName']; $initialize[] = sprintf($templateRelation, 'hasMany', $relation['fields'], $entityName, $relation['relationFields']); } } } } if (isset($this->_options['belongsTo'])) { if (count($this->_options['belongsTo'])) { foreach ($this->_options['belongsTo'] as $relation) { if (is_string($relation['fields'])) { $entityName = $relation['referencedModel']; $initialize[] = sprintf($templateRelation, 'belongsTo', $relation['fields'], $entityName, $relation['relationFields']); } } } } if (isset($this->_options['foreignKeys'])) { if (count($this->_options['foreignKeys']) && is_array($this->_options['foreignKeys'])) { foreach ($this->_options['foreignKeys'] as $foreignKey) { $initialize[] = sprintf($templateRelation, 'addForeignKey', $foreignKey['fields'], $foreignKey['entity'], $foreignKey['referencedFields']); } } } $alreadyInitialized = false; $alreadyValidations = false; if (file_exists($modelPath)) { try { $possibleMethods = array(); if ($useSettersGetters) { foreach ($fields as $field) { $methodName = Utils::camelize($field->getName()); $possibleMethods['set' . $methodName] = true; $possibleMethods['get' . $methodName] = true; } } require $modelPath; $linesCode = file($modelPath); $reflection = new \ReflectionClass($this->_options['className']); foreach ($reflection->getMethods() as $method) { if ($method->getDeclaringClass()->getName() == $this->_options['className']) { $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()); } } if (count($validations)) { $validations[] = $templateValidationFailed; } /** * Check if there has been an extender class */ $extends = '\\Phalcon\\Mvc\\Model'; if (isset($this->_options['extends'])) { if (!empty($this->_options['extends'])) { $extends = $this->_options['extends']; } } /** * 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 = Utils::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, join('', $initialize)); } else { $initCode = ""; } } else { $initCode = ""; } $license = ''; if (file_exists('license.txt')) { $license = file_get_contents('license.txt'); } $content = join('', $attributes); if ($useSettersGetters) { $content .= join('', $setters) . join('', $getters); } $content .= $validationsCode . $initCode; foreach ($methodRawCode as $methodCode) { $content .= $methodCode; } if ($genDocMethods) { $content .= sprintf($templateFind, $className, $className); } if (isset($this->_options['mapColumn'])) { $content .= $this->_genColumnMapCode($fields); } $code = sprintf($templateCode, $license, $namespace, $className, $extends, $content); file_put_contents($modelPath, $code); print Color::success('Model "' . $this->_options['name'] . '" was successfully created.') . PHP_EOL; }
/** * Build project * * @return bool */ public function build() { $this->buildDirectories()->getVariableValues()->createConfig()->createBootstrapFiles()->createDefaultTasks()->createLauncher(); print Color::success(sprintf('You can create a symlink to %s to invoke the application', $this->options->get('projectPath') . 'run')) . PHP_EOL; return true; }
public function build() { if (!$this->_options['name']) { throw new BuilderException("You must specify the table name"); } $path = ''; if (isset($this->_options['directory'])) { if ($this->_options['directory']) { $path = $this->_options['directory'] . '/'; } } $config = $this->_getConfig($path); if (!isset($this->_options['modelsDir'])) { if (!isset($config->application->modelsDir)) { throw new BuilderException("Builder doesn't knows where is the models directory"); } $modelsDir = $config->application->modelsDir; } else { $modelsDir = $this->_options['modelsDir']; } if ($this->isAbsolutePath($modelsDir) == false) { $modelPath = $path . "public" . DIRECTORY_SEPARATOR . $modelsDir; } else { $modelPath = $modelsDir; } $methodRawCode = array(); $className = $this->_options['className']; $modelPath .= $className . '.php'; if (file_exists($modelPath)) { if (!$this->_options['force']) { throw new BuilderException("The model file '" . $className . ".php' already exists in models dir"); } } 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]"); } if (isset($this->_options['namespace'])) { $namespace = 'namespace ' . $this->_options['namespace'] . ';' . PHP_EOL . PHP_EOL; $methodRawCode[] = "\t" . 'public function getSource()' . "\n\t" . '{' . "\n\t\t" . 'return "' . $this->_options['name'] . '";' . "\n\t" . '}'; } else { $namespace = ''; } $useSettersGetters = $this->_options['genSettersGetters']; if (isset($this->_options['genDocMethods'])) { $genDocMethods = $this->_options['genDocMethods']; } else { $genDocMethods = false; } $adapter = $config->database->adapter; $this->isSupportedAdapter($adapter); $adapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $adapter; $db = new $adapter(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'name' => $config->database->name)); $initialize = array(); if (isset($this->_options['schema'])) { if ($this->_options['schema'] != $config->database->name) { $initialize[] = "\t\t\$this->setSchema(\"{$this->_options['schema']}\");"; } $schema = $this->_options['schema']; } else { $schema = $config->database->name; } if ($this->_options['fileName'] != $this->_options['name']) { $initialize[] = "\t\t\$this->setSource(\"{$this->_options['name']}\");"; } $table = $this->_options['name']; if ($db->tableExists($table, $schema)) { $fields = $db->describeColumns($table, $schema); } else { throw new BuilderException('Table "' . $table . '" does not exists'); } if (isset($this->_options['hasMany'])) { if (count($this->_options['hasMany'])) { foreach ($this->_options['hasMany'] as $entityName => $relation) { if (is_string($relation['fields'])) { if (preg_match('/_id$/', $relation['relationFields']) && $relation['fields'] == 'id') { $initialize[] = "\t\t\$this->hasMany(\"{$relation['fields']}\", \"{$entityName}\", \"{$relation['relationFields']}\")"; } else { $initialize[] = "\t\t\$this->hasMany(\"{$relation['fields']}\", \"{$entityName}\", \"{$relation['relationFields']}\")"; } } } } } if (isset($this->_options['belongsTo'])) { if (count($this->_options['belongsTo'])) { foreach ($this->_options['belongsTo'] as $entityName => $relation) { if (is_string($relation['fields'])) { if (preg_match('/_id$/', $relation['fields']) && $relation['relationFields'] == 'id') { $initialize[] = "\t\t\$this->belongsTo(\"{$relation['fields']}\", \"{$entityName}\", \"{$relation['relationFields']}\")"; } else { $initialize[] = "\t\t\$this->belongsTo(\"{$relation['fields']}\", \"{$entityName}\", \"{$relation['relationFields']}\")"; } } } } } if (isset($this->_options['foreignKeys'])) { if (count($this->_options['foreignKeys']) && is_array($this->_options['foreignKeys'])) { foreach ($this->_options['foreignKeys'] as $foreignKey) { $initialize[] = "\t\t\$this->addForeignKey(\"{$foreignKey['fields']}\", \"{$foreignKey['entity']}\", \"{$foreignKey['referencedFields']}\")"; } } } $alreadyInitialized = false; $alreadyValidations = false; if (file_exists($modelPath)) { try { $posibleMethods = array(); if ($useSettersGetters) { foreach ($fields as $field) { $methodName = Utils::camelize($field->getName()); $posibleMethods['set' . $methodName] = true; $posibleMethods['get' . $methodName] = true; } } require $modelPath; $linesCode = file($modelPath); $reflection = new \ReflectionClass($this->_options['className']); foreach ($reflection->getMethods() as $method) { if ($method->getDeclaringClass()->getName() == $this->_options['className']) { $methodName = $method->getName(); if (!isset($posibleMethods[$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() === \Phalcon\Db\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[] = "\t\t\$this->validate(new InclusionIn(array(\n\t\t\t\"field\" => \"{$field->getName()}\",\n\t\t\t\"domain\" => array({$varItems}),\n\t\t\t\"required\" => true\n\t\t)))"; } } if ($field->getName() == 'email') { $validations[] = "\t\t\$this->validate(new Email(array(\n\t\t\t\"field\" => \"{$field->getName()}\",\n\t\t\t\"required\" => true\n\t\t)))"; } } if (count($validations)) { $validations[] = "\t\tif (\$this->validationHasFailed() == true) {\n\t\t\treturn false;\n\t\t}"; } $attributes = array(); $setters = array(); $getters = array(); foreach ($fields as $field) { $type = $this->getPHPType($field->getType()); if ($useSettersGetters) { $attributes[] = "\t/**\n\t * @var {$type}\n\t *\n\t */\n\tprotected \${$field->getName()};\n"; $setterName = Utils::camelize($field->getName()); $setters[] = "\t/**\n\t * Method to set the value of field {$field->getName()}\n\t *\n\t * @param {$type} \${$field->getName()}\n\t */\n\tpublic function set{$setterName}(\${$field->getName()})\n\t{\n\t\t\$this->{$field->getName()} = \${$field->getName()};\n\t}\n"; if (isset($this->_typeMap[$type])) { $getters[] = "\t/**\n\t * Returns the value of field {$field->getName()}\n\t *\n\t * @return {$type}\n\t */\n\tpublic function get{$setterName}()\n\t{\n\t\tif (\$this->{$field->getName()}) {\n\t\t\treturn new {$this->_typeMap[$type]}(\$this->{$field->getName()});\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n"; } else { $getters[] = "\t/**\n\t * Returns the value of field {$field->getName()}\n\t *\n\t * @return {$type}\n\t */\n\tpublic function get{$setterName}()\n\t{\n\t\treturn \$this->{$field->getName()};\n\t}\n"; } } else { $attributes[] = "\t/**\n\t * @var {$type}\n\t *\n\t */\n\tpublic \${$field->getName()};\n"; } } if ($alreadyValidations == false) { if (count($validations) > 0) { $validationsCode = "\n\t/**\n\t * Validations and business logic \n\t */\n\tpublic function validation()\n\t{\t\t\n" . join(";\n", $validations) . "\n\t}\n"; } else { $validationsCode = ""; } } else { $validationsCode = ""; } if ($alreadyInitialized == false) { if (count($initialize) > 0) { $initCode = "\n\t/**\n\t * Initializer method for model.\n\t */\n\tpublic function initialize()\n\t{\t\t\n" . join(";\n", $initialize) . ";\n\t}\n"; } else { $initCode = ""; } } else { $initCode = ""; } $code = "<?php\n\n"; if (file_exists('license.txt')) { $code .= PHP_EOL . file_get_contents('license.txt'); } $code .= $namespace . "\nclass " . $className . " extends \\Phalcon\\Mvc\\Model \n{\n\n" . join("\n", $attributes) . "\n"; if ($useSettersGetters) { $code .= "\n" . join("\n", $setters) . "\n\n" . join("\n", $getters); } $code .= $validationsCode . $initCode . "\n"; foreach ($methodRawCode as $methodCode) { $code .= $methodCode . PHP_EOL; } if ($genDocMethods) { $code .= "\n\t/**\n\t * @return " . $className . "[]\n\t */\n"; $code .= "\tpublic static function find(\$parameters=array())\n\t{\n"; $code .= "\t\treturn parent::find(\$parameters);\n"; $code .= "\t}\n\n"; $code .= "\n\t/**\n\t * @return " . $className . "\n\t */\n"; $code .= "\tpublic static function findFirst(\$parameters=array())\n\t{\n"; $code .= "\t\treturn parent::findFirst(\$parameters);\n"; $code .= "\t}\n\n"; } $code .= "}\n"; $code = str_replace("\t", " ", $code); file_put_contents($modelPath, $code); print Color::success('Model "' . $this->_options['name'] . '" was successfully created.') . PHP_EOL; }
/** * Build project * * @param $name * @param $path * @param $templatePath * @param $options * * @return bool */ public function build($name, $path, $templatePath, $options) { $this->buildDirectories($this->_dirs, $path); $this->getVariableValues($options); $this->createConfig($path, $templatePath); /*if (isset($options['useConfigIni']) && $options['useConfigIni']) { $this->createConfig($path, $templatePath, 'ini'); } else { $this->createConfig($path, $templatePath, 'php'); }*/ $this->createBootstrapFiles($path, $templatePath); $this->createDefaultTasks($path, $templatePath); $this->createLauncher($name, $path, $templatePath); $pathSymLink = realpath($path . $name); print Color::success("You can create a symlink to {$pathSymLink} to invoke the application") . PHP_EOL; return true; }
/** * List migrations along with statuses * * @param array $options * * @throws Exception * @throws ModelException * @throws ScriptException * */ public static function listAll(array $options) { // Define versioning type to be used if (true === $options['tsBased']) { VersionCollection::setType(VersionCollection::TYPE_TIMESTAMPED); } else { VersionCollection::setType(VersionCollection::TYPE_INCREMENTAL); } $migrationsDir = rtrim($options['migrationsDir'], '/'); if (!file_exists($migrationsDir)) { throw new ModelException('Migrations directory was not found.'); } /** @var Config $config */ $config = $options['config']; if (!$config instanceof Config) { throw new ModelException('Internal error. Config should be an instance of \\Phalcon\\Config'); } // Init ModelMigration if (!isset($config->database)) { throw new ScriptException('Cannot load database configuration'); } $finalVersion = null; if (isset($options['version']) && $options['version'] !== null) { $finalVersion = VersionCollection::createItem($options['version']); } $versionItems = ModelMigration::scanForVersions($migrationsDir); if (!isset($versionItems[0])) { throw new ModelException('Migrations were not found at ' . $migrationsDir); } // Set default final version if ($finalVersion === null) { $finalVersion = VersionCollection::maximum($versionItems); } ModelMigration::setup($config->database); ModelMigration::setMigrationPath($migrationsDir); self::connectionSetup($options); $initialVersion = self::getCurrentVersion($options); $completedVersions = self::getCompletedVersions($options); if ($finalVersion->getStamp() < $initialVersion->getStamp()) { $direction = ModelMigration::DIRECTION_BACK; $versionItems = VersionCollection::sortDesc($versionItems); } else { $direction = ModelMigration::DIRECTION_FORWARD; $versionItems = VersionCollection::sortAsc($versionItems); } foreach ($versionItems as $versionItem) { if (ModelMigration::DIRECTION_FORWARD === $direction && isset($completedVersions[(string) $versionItem])) { print Color::success('Version ' . (string) $versionItem . ' was already applied'); continue; } elseif (ModelMigration::DIRECTION_BACK === $direction && !isset($completedVersions[(string) $versionItem])) { print Color::success('Version ' . (string) $versionItem . ' was already rolled back'); continue; } if (ModelMigration::DIRECTION_FORWARD === $direction) { print Color::error('Version ' . (string) $versionItem . ' was not applied'); continue; } elseif (ModelMigration::DIRECTION_BACK === $direction) { print Color::error('Version ' . (string) $versionItem . ' was not rolled back'); continue; } } }