Exemplo n.º 1
0
 /**
  * {@inheritdoc}
  *
  * @return void
  */
 public function getHelp()
 {
     print Color::head('Help:') . PHP_EOL;
     print Color::colorize('  Creates a module') . PHP_EOL . PHP_EOL;
     print Color::head('Example') . PHP_EOL;
     print Color::colorize('  phalcon module backend', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     $this->printParameters($this->getPossibleParams());
 }
Exemplo n.º 2
0
 /**
  * Prints help on the usage of the command
  *
  */
 public function getHelp()
 {
     print Color::head('Help:') . PHP_EOL;
     print Color::colorize('  Enables/disables webtools in a project') . PHP_EOL . PHP_EOL;
     print Color::head('Usage:') . PHP_EOL;
     print Color::colorize('  webtools [action]', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     print Color::head('Arguments:') . PHP_EOL;
     print Color::colorize('  ?', Color::FG_GREEN);
     print Color::colorize("\tShows this help text") . PHP_EOL . PHP_EOL;
     $this->printParameters($this->_possibleParameters);
 }
Exemplo n.º 3
0
 /**
  * Prints the help for current command.
  *
  * @return void
  */
 public function getHelp()
 {
     print Color::head('Help:') . PHP_EOL;
     print Color::colorize('  Creates a controller') . PHP_EOL . PHP_EOL;
     print Color::head('Usage:') . PHP_EOL;
     print Color::colorize('  controller [name] [directory]', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     print Color::head('Arguments:') . PHP_EOL;
     print Color::colorize('  ?', Color::FG_GREEN);
     print Color::colorize("\tShows this help text") . PHP_EOL . PHP_EOL;
     $this->printParameters($this->_possibleParameters);
 }
Exemplo n.º 4
0
 /**
  * {@inheritdoc}
  *
  * @return void
  */
 public function getHelp()
 {
     print Color::head('Help:') . PHP_EOL;
     print Color::colorize('  Creates a scaffold from a database table') . PHP_EOL . PHP_EOL;
     print Color::head('Usage:') . PHP_EOL;
     print Color::colorize('  scaffold [tableName] [options]', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     print Color::head('Arguments:') . PHP_EOL;
     print Color::colorize('  help', Color::FG_GREEN);
     print Color::colorize("\tShows this help text") . PHP_EOL . PHP_EOL;
     $this->printParameters($this->getPossibleParams());
 }
Exemplo n.º 5
0
 /**
  * Prints the help for current command.
  *
  * @return void
  */
 public function getHelp()
 {
     print Color::head('Help:') . PHP_EOL;
     print Color::colorize('  Creates a model') . PHP_EOL . PHP_EOL;
     print Color::head('Usage:') . PHP_EOL;
     print Color::colorize('  model [table-name] [options]', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     print Color::head('Arguments:') . PHP_EOL;
     print Color::colorize('  ?', Color::FG_GREEN);
     print Color::colorize("\tShows this help text") . PHP_EOL . PHP_EOL;
     $this->printParameters($this->_possibleParameters);
 }
Exemplo n.º 6
0
 /**
  * Prints the help for current command.
  *
  * @return void
  */
 public function getHelp()
 {
     print Color::head('Help:') . PHP_EOL;
     print Color::colorize('  Creates a project') . PHP_EOL . PHP_EOL;
     print Color::head('Usage:') . PHP_EOL;
     print Color::colorize('  project [name] [type] [directory] [enable-webtools]', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     print Color::head('Arguments:') . PHP_EOL;
     print Color::colorize('  help', Color::FG_GREEN);
     print Color::colorize("\tShows this help text") . PHP_EOL . PHP_EOL;
     print Color::head('Example') . PHP_EOL;
     print Color::colorize('  phalcon project store simple', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     $this->printParameters($this->_possibleParameters);
 }
Exemplo n.º 7
0
 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;
 }
Exemplo n.º 8
0
 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;
 }
Exemplo n.º 9
0
 /**
  * Prints the available options in the script
  *
  * @param array $parameters
  */
 public function printParameters($parameters)
 {
     $length = 0;
     foreach ($parameters as $parameter => $description) {
         if ($length == 0) {
             $length = strlen($parameter);
         }
         if (strlen($parameter) > $length) {
             $length = strlen($parameter);
         }
     }
     print Color::head('Options:') . PHP_EOL;
     foreach ($parameters as $parameter => $description) {
         print Color::colorize(' --' . $parameter . str_repeat(' ', $length - strlen($parameter)), Color::FG_GREEN);
         print Color::colorize("    " . $description) . PHP_EOL;
     }
 }
Exemplo n.º 10
0
 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');
     } elseif ($adapter == 'Postgresql') {
         $schema = 'public';
     } else {
         $schema = isset($config->database->schema) ? $config->database->schema : $config->database->dbname;
     }
     $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;
             }
         }
     }
 }
Exemplo n.º 11
0
 /**
  * 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;
     }
 }
Exemplo n.º 12
0
 /**
  * Initialize task
  */
 public function mainAction()
 {
     // define error handler
     $this->setSilentErrorHandler();
     try {
         // init configurations // init logger
         $this->setConfig($this->getDI()->get('config'))->setLogger();
         // run server
         $this->sonar = new Application($this->getConfig());
         $this->sonar->run();
     } catch (AppServiceException $e) {
         echo Color::colorize($e->getMessage(), Color::FG_RED, Color::AT_BOLD) . PHP_EOL;
         if ($this->logger != null) {
             // logging all error exceptions
             $this->getLogger()->log($e->getMessage(), Logger::CRITICAL);
         }
     }
 }
Exemplo n.º 13
0
 public function build()
 {
     $path = '.';
     if (isset($this->_options['directory'])) {
         $path = $this->_options['directory'];
     }
     $config = $this->_getConfig($path . '/');
     $modelsDir = $config->application->modelsDir;
     $forceProcess = $this->_options['force'];
     if (isset($this->_options['defineRelations'])) {
         $defineRelations = $this->_options['defineRelations'];
     } else {
         $defineRelations = false;
     }
     if (isset($this->_options['foreignKeys'])) {
         $defineForeignKeys = $this->_options['foreignKeys'];
     } else {
         $defineForeignKeys = false;
     }
     if (isset($this->_options['genSettersGetters'])) {
         $genSettersGetters = $this->_options['genSettersGetters'];
     } else {
         $genSettersGetters = 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']);
     /**
      * @var $db \Phalcon\Db\Adapter\Pdo
      */
     $db = new $adapterName($configArray);
     if (isset($this->_options['schema'])) {
         $schema = $this->_options['schema'];
     } elseif ($adapter == 'Postgresql') {
         $schema = 'public';
     } else {
         $schema = isset($config->database->schema) ? $config->database->schema : $config->database->dbname;
     }
     $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 = Utils::camelize($name);
         if (!file_exists($modelsDir . '/' . $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 \Phalcon\Builder\Model(array('name' => $name, 'schema' => $schema, 'extends' => isset($this->_options['extends']) ? $this->_options['extends'] : null, 'namespace' => $this->_options['namespace'], 'force' => $forceProcess, 'hasMany' => $hasManyModel, 'belongsTo' => $belongsToModel, 'foreignKeys' => $foreignKeysModel, 'genSettersGetters' => $genSettersGetters, 'directory' => $this->_options['directory']));
             $modelBuilder->build();
         } else {
             if ($this->isConsole()) {
                 print Color::info("Skipping model \"{$name}\" because it already exist");
             } else {
                 $this->exist[] = $name;
             }
         }
     }
 }
Exemplo n.º 14
0
 /**
  * {@inheritdoc}
  *
  * @return void
  */
 public function getHelp()
 {
     print Color::head('Help:') . PHP_EOL;
     print Color::colorize('  Generates/Run a Migration') . PHP_EOL . PHP_EOL;
     print Color::head('Usage: Generate a Migration') . PHP_EOL;
     print Color::colorize('  migration generate', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     print Color::head('Usage: Run a Migration') . PHP_EOL;
     print Color::colorize('  migration run', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     print Color::head('Arguments:') . PHP_EOL;
     print Color::colorize('  help', Color::FG_GREEN);
     print Color::colorize("\tShows this help text") . PHP_EOL . PHP_EOL;
     $this->printParameters($this->getPossibleParams());
 }
Exemplo n.º 15
0
use Phalcon\Commands\CommandsListener;
use Phalcon\Loader;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Exception as PhalconException;
try {
    if (!extension_loaded('phalcon')) {
        throw new Exception("Phalcon extension isn't installed, follow these instructions to install it: " . 'https://docs.phalconphp.com/en/latest/reference/install.html');
    }
    $loader = new Loader();
    $loader->registerDirs(array(__DIR__ . '/scripts/'))->registerNamespaces(array('Phalcon' => __DIR__ . '/scripts/'))->register();
    if (Version::getId() < Script::COMPATIBLE_VERSION) {
        throw new Exception(sprintf("Your Phalcon version isn't compatible with Developer Tools, download the latest at: %s", Script::DOC_DOWNLOAD_URL));
    }
    defined('TEMPLATE_PATH') || define('TEMPLATE_PATH', __DIR__ . '/templates');
    $vendor = sprintf('Phalcon DevTools (%s)', Version::get());
    print PHP_EOL . Color::colorize($vendor, Color::FG_GREEN, Color::AT_BOLD) . PHP_EOL . PHP_EOL;
    $eventsManager = new EventsManager();
    $eventsManager->attach('command', new CommandsListener());
    $script = new Script($eventsManager);
    $commandsToEnable = array('\\Phalcon\\Commands\\Builtin\\Enumerate', '\\Phalcon\\Commands\\Builtin\\Controller', '\\Phalcon\\Commands\\Builtin\\Module', '\\Phalcon\\Commands\\Builtin\\Model', '\\Phalcon\\Commands\\Builtin\\AllModels', '\\Phalcon\\Commands\\Builtin\\Project', '\\Phalcon\\Commands\\Builtin\\Scaffold', '\\Phalcon\\Commands\\Builtin\\Migration', '\\Phalcon\\Commands\\Builtin\\Webtools');
    foreach ($commandsToEnable as $command) {
        $script->attach(new $command($script, $eventsManager));
    }
    $script->run();
} catch (PhalconException $e) {
    fwrite(STDERR, Color::error($e->getMessage()) . PHP_EOL);
    exit(1);
} catch (Exception $e) {
    fwrite(STDERR, 'ERROR: ' . $e->getMessage() . PHP_EOL);
    exit(1);
}
Exemplo n.º 16
0
 /**
  * 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;
 }
Exemplo n.º 17
0
 /**
  * Shows a success notification
  *
  * @param string $message
  */
 protected function _notifySuccess($message)
 {
     print Color::success($message);
 }
Exemplo n.º 18
0
 /**
  * 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);
 }
Exemplo n.º 19
0
 /**
  * {@inheritdoc}
  *
  * @return void
  */
 public function getHelp()
 {
     echo Color::head('Help:') . PHP_EOL;
     echo Color::colorize('  Enables/disables webtools in a project') . PHP_EOL . PHP_EOL;
     print Color::head('Usage: Enable webtools') . PHP_EOL;
     print Color::colorize('  webtools enable', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     print Color::head('Usage: Disable webtools') . PHP_EOL;
     print Color::colorize('  webtools disable', Color::FG_GREEN) . PHP_EOL . PHP_EOL;
     echo Color::head('Arguments:') . PHP_EOL;
     echo Color::colorize('  help', Color::FG_GREEN);
     echo Color::colorize("\tShows this help text") . PHP_EOL . PHP_EOL;
     $this->printParameters($this->getPossibleParams());
 }
Exemplo n.º 20
0
 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;
 }
Exemplo n.º 21
0
        $extensionLoaded = false;
        include dirname(__FILE__) . '/scripts/Phalcon/Script.php';
        throw new Exception(sprintf("Phalcon extension isn't installed, follow these instructions to install it: %s", Script::DOC_INSTALL_URL));
    }
    $loader = new Loader();
    $loader->registerDirs(array(__DIR__ . '/scripts/'))->registerNamespaces(array('Phalcon' => __DIR__ . '/scripts/'))->register();
    if (Version::getId() < Script::COMPATIBLE_VERSION) {
        throw new Exception(sprintf("Your Phalcon version isn't compatible with Developer Tools, download the latest at: %s", Script::DOC_DOWNLOAD_URL));
    }
    if (!defined('TEMPLATE_PATH')) {
        define('TEMPLATE_PATH', __DIR__ . '/templates');
    }
    $vendor = sprintf('Phalcon DevTools (%s)', Version::get());
    print PHP_EOL . Color::colorize($vendor, Color::FG_GREEN, Color::AT_BOLD) . PHP_EOL . PHP_EOL;
    $eventsManager = new EventsManager();
    $eventsManager->attach('command', new CommandsListener());
    $script = new Script($eventsManager);
    $commandsToEnable = array('\\Phalcon\\Commands\\Builtin\\Enumerate', '\\Phalcon\\Commands\\Builtin\\Controller', '\\Phalcon\\Commands\\Builtin\\Model', '\\Phalcon\\Commands\\Builtin\\AllModels', '\\Phalcon\\Commands\\Builtin\\Project', '\\Phalcon\\Commands\\Builtin\\Scaffold', '\\Phalcon\\Commands\\Builtin\\Migration', '\\Phalcon\\Commands\\Builtin\\Webtools');
    foreach ($commandsToEnable as $command) {
        $script->attach(new $command($script, $eventsManager));
    }
    $script->run();
} catch (PhalconException $e) {
    print Color::error($e->getMessage()) . PHP_EOL;
} catch (Exception $e) {
    if ($extensionLoaded) {
        print Color::error($e->getMessage()) . PHP_EOL;
    } else {
        print 'ERROR: ' . $e->getMessage() . PHP_EOL;
    }
}
Exemplo n.º 22
0
 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;
 }
Exemplo n.º 23
0
 /**
  * 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;
     }
 }
Exemplo n.º 24
0
 /**
  * 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;
 }
Exemplo n.º 25
0
 /**
  * {@inheritdoc}
  *
  * @return void
  */
 public function getHelp()
 {
     print Color::head('Help:') . PHP_EOL;
     print Color::colorize('  Lists the commands available in Phalcon devtools') . PHP_EOL . PHP_EOL;
     $this->run([]);
 }
Exemplo n.º 26
0
 /**
  * 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;
         }
     }
 }