예제 #1
0
 public function pageAction()
 {
     $pageSlug = $this->getUriParameter('pageSlug');
     $pageTitle = \Phalcon\Text::camelize($pageSlug);
     $this->tag->setTitle($pageTitle);
     $this->view->pick('pages/' . $pageSlug);
 }
예제 #2
0
 protected function prepare(Type $type)
 {
     if (!$this->getConnection()->tableExists($this->table)) {
         throw new Exception("Table {$this->table} does not exist");
     }
     $name = $this->table;
     if ($this->tablePrefix && Text::startsWith($name, $this->tablePrefix)) {
         $name = substr($name, strlen($this->tablePrefix));
         $name = trim($name, '_');
     }
     if (empty($name)) {
         throw new Exception("Cannot infer model name from '{$this->table}'");
     }
     $name = Inflect::singularize($name);
     $model_name = Text::camelize($name);
     $vars['type'] = $type;
     $vars['namespace'] = $this->namespace;
     $vars['model_name'] = $model_name;
     $vars['table_name'] = $this->table;
     $vars['connection'] = $this->connectionService;
     $vars['name'] = str_replace('_', ' ', ucfirst($name));
     $vars['url'] = '/' . str_replace('_', '-', $name);
     $vars['primary_key'] = $this->primaryKey;
     return $vars;
 }
예제 #3
0
파일: Camelize.php 프로젝트: arius86/core
 /**
  * {@inheritdoc}
  */
 public function resolve(&$value)
 {
     if (is_string($value) && strlen($value) > 0) {
         $value = \Phalcon\Text::camelize($value);
     }
     return $value;
 }
예제 #4
0
파일: Ui.php 프로젝트: skullab/area51
 public function __get($name)
 {
     if ($this->getDI()->has($name)) {
         return parent::__get($name);
     }
     return $this->{lcfirst(\Phalcon\Text::camelize("get_{$name}"))}();
 }
예제 #5
0
파일: Loader.php 프로젝트: szytko/core
 /**
  * Extract Vegas modules from composer vegas-cmf vendors.
  *
  * @param $modulesList
  * @return mixed
  */
 private function dumpModulesFromVendor(array &$modulesList)
 {
     if (!file_exists(APP_ROOT . '/composer.json')) {
         return $modulesList;
     }
     $fileContent = file_get_contents(APP_ROOT . DIRECTORY_SEPARATOR . 'composer.json');
     $json = json_decode($fileContent, true);
     $vendorDir = realpath(APP_ROOT . (isset($json['config']['vendor-dir']) ? DIRECTORY_SEPARATOR . $json['config']['vendor-dir'] : DIRECTORY_SEPARATOR . 'vendor'));
     $vendorDir .= DIRECTORY_SEPARATOR . 'vegas-cmf';
     $directoryIterator = new \DirectoryIterator($vendorDir);
     foreach ($directoryIterator as $libDir) {
         if ($libDir->isDot()) {
             continue;
         }
         //creates path to Module.php file
         $moduleSettingsFile = implode(DIRECTORY_SEPARATOR, [$vendorDir, $libDir, 'module', self::MODULE_SETTINGS_FILE]);
         if (!file_exists($moduleSettingsFile)) {
             continue;
         }
         $baseName = Text::camelize($libDir->getBasename());
         if (!isset($modulesList[$baseName])) {
             $modulesList[$baseName] = ['className' => $baseName . '\\' . pathinfo(self::MODULE_SETTINGS_FILE, PATHINFO_FILENAME), 'path' => $moduleSettingsFile];
         }
     }
     return $modulesList;
 }
 public function resetAction()
 {
     $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($this->config->database->toArray());
     $tables = $connection->listTables();
     foreach ($tables as $table) {
         $tablename = \Phalcon\Text::camelize($table);
         $fd = fopen("{$this->config->application->formsDir}/{$tablename}Form.php", "w");
         fwrite($fd, "<?php" . self::NL . self::NL);
         // Begin class
         fwrite($fd, "class {$tablename}Form {" . self::NL);
         $columns = $connection->describeColumns($table);
         foreach ($columns as $column) {
             if ($column instanceof \Phalcon\Db\Column) {
                 // Escape if column is primary
                 if ($column->isPrimary()) {
                     continue;
                 }
                 // Begin method
                 $columnname = \Phalcon\Text::camelize($column->getName());
                 fwrite($fd, self::TAB . "private function _{$columnname}() {" . self::NL);
                 // Write element
                 $columntype_base = $this->_getBaseType($column->getType());
                 $columntype = $this->_getType($columntype_base, $column);
                 fwrite($fd, self::TAB . self::TAB . "\$element = new \\Phalcon\\Forms\\Element\\{$columntype}(\"{$columnname}\");" . self::NL);
                 fwrite($fd, self::TAB . self::TAB . "\$element->setLabel(\"{$columnname}\");" . self::NL);
                 // Add empty selection for select fields
                 if ($columntype == "Select") {
                     fwrite($fd, self::TAB . self::TAB . "\$element->setOptions([]);" . self::NL);
                 }
                 // Add validator on text fields
                 if ($columntype == "Text" && $column->getSize() > 0) {
                     fwrite($fd, self::TAB . self::TAB . "\$element->addValidator(new \\Phalcon\\Validation\\Validator\\StringLength([" . self::NL);
                     fwrite($fd, self::TAB . self::TAB . self::TAB . "\"max\" => {$column->getSize()}" . self::NL);
                     fwrite($fd, self::TAB . self::TAB . "]));" . self::NL);
                 }
                 // End method
                 fwrite($fd, self::TAB . self::TAB . "return \$element;" . self::NL);
                 fwrite($fd, self::TAB . "}" . self::NL);
             }
         }
         // Final method : construction of the form
         fwrite($fd, self::TAB . "public function setFields() {" . self::NL);
         foreach ($columns as $column) {
             if ($column instanceof \Phalcon\Db\Column) {
                 if ($column->isPrimary()) {
                     continue;
                 }
                 $columnname = \Phalcon\Text::camelize($column->getName());
                 fwrite($fd, self::TAB . self::TAB . "\$this->add(\$this->_{$columnname}());" . self::NL);
             }
         }
         fwrite($fd, self::TAB . "}" . self::NL);
         // End class
         fwrite($fd, "}" . self::NL . self::NL);
         fclose($fd);
     }
     $this->view->disable();
     echo "done!";
     return FALSE;
 }
예제 #7
0
 /**
  * Return menu options
  *
  * @return array
  */
 public function getMenuOptions()
 {
     $this->_limitParamValue = 100;
     $rows = $this->getColumnData();
     $acl = $this->_di->get('acl');
     $viewer = $this->_di->get('viewer');
     $options = [];
     foreach ($rows as $row) {
         $option = [];
         $option['id'] = $row['id'];
         $option['text'] = $row['title'];
         if ($row['module'] && $row['controller']) {
             if (!$acl->isAllowed($viewer->getRole(), \Engine\Acl\Dispatcher::ACL_ADMIN_MODULE, \Engine\Acl\Dispatcher::ACL_ADMIN_CONTROLLER, '*') && !$acl->isAllowed($viewer->getRole(), \Engine\Acl\Dispatcher::ACL_ADMIN_MODULE, \Engine\Acl\Dispatcher::ACL_ADMIN_CONTROLLER, 'read')) {
                 if (!$acl->isAllowed($viewer->getRole(), $row['module'], $row['controller'], 'read')) {
                     continue;
                 }
             }
             $option['controller'] = \Phalcon\Text::camelize($row['module']) . ".controller." . \Phalcon\Text::camelize($row['controller']);
             $option['moduleName'] = \Phalcon\Text::camelize($row['module']);
             $option['controllerName'] = \Phalcon\Text::camelize($row['controller']);
             $option['leaf'] = true;
             $option['cls'] = 'window-list-item';
             $option['iconCls'] = 'window-list-item-icon';
         }
         $option['qtip'] = $row['description'];
         $options[] = $option;
     }
     return $options;
 }
예제 #8
0
 /**
  * @param string $name
  * @return mixed
  */
 public function __get($name)
 {
     $getter = 'get' . \Phalcon\Text::camelize($name);
     if (method_exists($this, $getter)) {
         return $this->{$getter}();
     }
     return null;
 }
예제 #9
0
파일: myTools.php 프로젝트: huoybb/support
 public static function camelize($title)
 {
     $words = explode(' ', trim($title));
     foreach ($words as $key => $word) {
         $words[$key] = \Phalcon\Text::camelize($word);
     }
     return implode(' ', $words);
 }
예제 #10
0
 private function correctCase($key)
 {
     if (strpos($key, '_')) {
         return lcfirst(Text::camelize($key));
     } else {
         return $key;
     }
 }
예제 #11
0
 public function createAction($r_controller = null, $r_action = null, $r_id = null)
 {
     $mapServerConfig = $this->getDI()->getConfig()->mapserver;
     $fileName = $mapServerConfig->mapfileCacheDir . $mapServerConfig->contextesCacheDir . $this->request->getPost("code") . ".map";
     //Ne pas créer le contexte si il y en a déjà un avec le même code
     if (file_exists($fileName)) {
         $this->flash->error("Le fichier {$fileName} existe déjà!");
         return $this->dispatcher->forward(array("controller" => $this->ctlName, "action" => "new", "param" => !is_null($r_id) ? "/" . $r_controller . "/" . $r_action . "/" . $r_id : ""));
     }
     $idContexteADupliquer = $this->request->getPost('id_contexte_a_dupliquer');
     //On désire dupliquer un contexte
     if ($idContexteADupliquer) {
         if (!$this->peutDupliquerContexte($idContexteADupliquer)) {
             $this->flash->error("Vous n'avez pas la permission de dupliquer le contexte {$idContexteADupliquer}.");
             return $this->dispatcher->forward(array("controller" => $this->ctlName, "action" => "new", "param" => !is_null($r_id) ? "/" . $r_controller . "/" . $r_action . "/" . $r_id : ""));
         }
     }
     $this->traiterCodeOnlineRessource();
     $igoContexte = new IgoContexte();
     $igoContexte->mode = $this->request->getPost("mode");
     $igoContexte->position = $this->request->getPost("position");
     $igoContexte->zoom = $this->request->getPost("zoom");
     $igoContexte->code = $this->request->getPost("code");
     $igoContexte->nom = $this->request->getPost("nom");
     $igoContexte->description = $this->request->getPost("description");
     $igoContexte->mf_map_def = $this->request->getPost("mf_map_def");
     $igoContexte->date_modif = $this->request->getPost("date_modif");
     $igoContexte->json = $this->request->getPost("json");
     $igoContexte->mf_map_projection = $this->request->getPost("mf_map_projection");
     $igoContexte->profil_proprietaire_id = $this->request->getPost("profil_proprietaire_id");
     if ($igoContexte->profil_proprietaire_id == "") {
         $igoContexte->profil_proprietaire_id = null;
     }
     //Valider la sélection ou pas du profil propriétaire
     if (!$this->validationProfilProprietaire($igoContexte->profil_proprietaire_id, $messageErreurProfilProprietaire)) {
         foreach ($messageErreurProfilProprietaire as $message) {
             $this->flash->error($message);
         }
         return $this->dispatcher->forward(array("controller" => $this->ctlName, "action" => "new", "param" => !is_null($r_id) ? "/" . $r_controller . "/" . $r_action . "/" . $r_id : ""));
     }
     $igoContexte->mf_map_meta_onlineresource = $this->request->getPost("mf_map_meta_onlineresource");
     $igoContexte->generer_onlineresource = $this->request->getPost("generer_onlineResource");
     try {
         if (!$igoContexte->save()) {
             foreach ($igoContexte->getMessages() as $message) {
                 $this->flash->error($message);
             }
             return $this->dispatcher->forward(array("controller" => $this->ctlName, "action" => "new", "param" => !is_null($r_id) ? "/" . $r_controller . "/" . $r_action . "/" . $r_id : ""));
         }
         if ($idContexteADupliquer) {
             $this->dupliquerContexte($idContexteADupliquer, $igoContexte->id);
         }
         $this->flash->success(Text::camelize(str_replace("igo_", "", $this->ctlName)) . " " . $igoContexte->id . " créé avec succès");
     } catch (\Exception $e) {
         $this->flash->error($e->getMessage());
         return $this->dispatcher->forward(array("controller" => $this->ctlName, "action" => "new", "param" => !is_null($r_id) ? "/" . $r_controller . "/" . $r_action . "/" . $r_id : ""));
     }
 }
예제 #12
0
 public static function camelize($module)
 {
     $tmpModuleNameArr = explode('-', $module);
     $moduleName = '';
     foreach ($tmpModuleNameArr as $part) {
         $moduleName .= \Phalcon\Text::camelize($part);
     }
     return $moduleName;
 }
예제 #13
0
 public function run($parameters)
 {
     $name = $this->getOption(array('name', 1));
     $className = Text::camelize(isset($parameters[2]) ? $parameters[2] : $name);
     $fileName = Text::uncamelize($className);
     $schema = $this->getOption('schema');
     $modelBuilder = new \Phalcon\Builder\Model(array('name' => $name, 'schema' => $schema, 'className' => $className, 'fileName' => $fileName, 'genSettersGetters' => $this->isReceivedOption('get-set'), 'genDocMethods' => $this->isReceivedOption('doc'), 'namespace' => $this->getOption('namespace'), 'directory' => $this->getOption('directory'), 'force' => $this->isReceivedOption('force')));
     $modelBuilder->build();
 }
예제 #14
0
 /**
  * @param Event               $event
  * @param DispatcherInterface $dispatcher
  */
 public function beforeDispatchLoop(Event $event, DispatcherInterface $dispatcher, $data)
 {
     if ($dispatcher->getActionName()) {
         $actionName = $dispatcher->getActionName();
         $actionName = Text::camelize($actionName);
         $actionName = lcfirst($actionName);
         $dispatcher->setActionName($actionName);
     }
 }
예제 #15
0
 /**
  * @param $parameters
  */
 public function run($parameters)
 {
     $name = $this->getOption(array('name', 1));
     $className = Text::camelize(isset($parameters[1]) ? $parameters[1] : $name);
     $fileName = Text::uncamelize($className);
     $schema = $this->getOption('schema');
     $modelBuilder = new ModelBuilder(array('name' => $name, 'schema' => $schema, 'className' => $className, 'fileName' => $fileName, 'genSettersGetters' => $this->isReceivedOption('get-set'), 'genDocMethods' => $this->isReceivedOption('doc'), 'namespace' => $this->getOption('namespace'), 'directory' => $this->getOption('directory'), 'modelsDir' => $this->getOption('output'), 'extends' => $this->getOption('extends'), 'excludeFields' => $this->getOption('excludefields'), 'force' => $this->isReceivedOption('force'), 'mapColumn' => $this->isReceivedOption('mapcolumn')));
     $modelBuilder->build();
 }
예제 #16
0
파일: Model.php 프로젝트: skullab/area51
 public function __get($name)
 {
     $name = \Phalcon\Text::camelize($name);
     foreach ($this->_namespaces as $dir) {
         if (class_exists("Thunderhawk\\API\\Mvc\\Model\\{$dir}\\{$name}")) {
             $class = "Thunderhawk\\API\\Mvc\\Model\\{$dir}\\{$name}";
             return new $class();
         }
     }
 }
예제 #17
0
 public function pageAction()
 {
     $pageSlug = $this->getUriParameter('pageSlug');
     $pageTitle = Text::camelize($pageSlug);
     $this->tag->setTitle($pageTitle);
     $this->view->pick('pages/' . $pageSlug);
     $this->view->setVar('isFrontpage', false);
     $this->view->setVar('isPage', $pageSlug);
     error_log('pageaction');
 }
예제 #18
0
 /**
  * Tests the camelize function
  *
  * @author Nikos Dimopoulos <*****@*****.**>
  * @since  2012-10-30
  */
 public function testCamelizeString()
 {
     $camelizeTests = array('camelize' => 'Camelize', 'CameLiZe' => 'Camelize', 'cAmeLize' => 'Camelize', '_camelize' => 'Camelize', '123camelize' => '123camelize', 'c_a_m_e_l_i_z_e' => 'CAMELIZE', 'Camelize' => 'Camelize', 'camel_ize' => 'CamelIze', 'CameLize' => 'Camelize', 'CAMELIZE' => 'Camelize', 'camelizE' => 'Camelize');
     $template = "Text::camelize did not convert the string '%s' correctly";
     foreach ($camelizeTests as $input => $camelized) {
         $expected = $camelized;
         $actual = PhText::camelize($input);
         $this->assertEquals($expected, $actual, sprintf($template, $input));
     }
 }
예제 #19
0
 public function pageAction()
 {
     $pageSlug = $this->getUriParameter('pageSlug');
     switch ($pageSlug) {
         case 'roadmap':
             return $this->response->redirect('https://github.com/phalcon/cphalcon/wiki/Roadmap');
     }
     $pageTitle = Text::camelize($pageSlug);
     $this->tag->setTitle($pageTitle);
     $this->view->pick('pages/' . $pageSlug);
     $this->view->setVar('isFrontpage', false);
     $this->view->setVar('isPage', $pageSlug);
 }
예제 #20
0
 public function renderAction($layout)
 {
     $layout = json_decode($layout, true);
     $output = array();
     array_walk($layout, array($this, 'category_type'));
     $table_set = false;
     foreach ($layout as $value) {
         $type = $value['type'];
         $category = $value['category'];
         if ($category == "database") {
             if (!$table_set) {
                 $controller = "\\PRIME\\FormElements\\" . ucwords($category) . "\\TableSelectController";
                 $tempController = new $controller();
                 $output[] = call_user_func(array($tempController, 'Render'));
             }
             $table_set = true;
         }
         $controller = "\\PRIME\\FormElements\\" . ucwords($category) . "\\" . PhText::camelize($type) . 'Controller';
         $tempController = new $controller();
         $arg = array();
         foreach ($value as $param_key => $param_val) {
             if ($param_key != 'type' && $param_key != 'category') {
                 $arg[] = $param_val;
             }
         }
         $output[] = call_user_func_array(array($tempController, 'Render'), $arg);
     }
     $data_out['style'] = array();
     $data_out['style'][] = "<style>";
     $data_out['html'] = array();
     $data_out['js'] = array();
     $data_out['js'][] = "<script>";
     foreach ($output as $param) {
         if (array_key_exists('style', $param)) {
             $data_out['style'] = array_merge($data_out['style'], $param['style']);
         }
         if (array_key_exists('html', $param)) {
             $data_out['html'] = array_merge($data_out['html'], $param['html']);
         }
         if (array_key_exists('js', $param)) {
             $data_out['js'] = array_merge($data_out['js'], $param['js']);
         }
     }
     $data_out['style'][] = "</style>";
     $data_out['js'][] = "</script>";
     return $this->echo_func($data_out, '');
 }
예제 #21
0
 /**
  * @return string
  * @throws \Phalcon\Builder\BuilderException
  */
 public function build()
 {
     if ($this->options->contains('directory')) {
         $this->path->setRootPath($this->options->get('directory'));
     }
     $namespace = '';
     if ($this->options->contains('namespace') && $this->checkNamespace($this->options->get('namespace'))) {
         $namespace = 'namespace ' . $this->options->get('namespace') . ';' . PHP_EOL . PHP_EOL;
     }
     $baseClass = $this->options->get('baseClass', '\\Phalcon\\Mvc\\Controller');
     if (!($controllersDir = $this->options->get('controllersDir'))) {
         $config = $this->getConfig();
         if (!isset($config->application->controllersDir)) {
             throw new BuilderException('Please specify a controller directory.');
         }
         $controllersDir = $config->application->controllersDir;
     }
     if (!$this->options->contains('name')) {
         throw new BuilderException('The controller name is required.');
     }
     $name = str_replace(' ', '_', $this->options->get('name'));
     $className = Utils::camelize($name);
     // Oops! We are in APP_PATH and try to get controllersDir from outside from project dir
     if ($this->isConsole() && substr($controllersDir, 0, 3) === '../') {
         $controllersDir = ltrim($controllersDir, './');
     }
     $controllerPath = rtrim($controllersDir, '\\/') . DIRECTORY_SEPARATOR . $className . "Controller.php";
     $code = "<?php\n\n" . $namespace . "class " . $className . "Controller extends " . $baseClass . "\n{\n\n\tpublic function indexAction()\n\t{\n\n\t}\n\n}\n\n";
     $code = str_replace("\t", "    ", $code);
     if (file_exists($controllerPath)) {
         if ($this->options->contains('force') && !is_writable($controllerPath)) {
             throw new BuilderException(sprintf('Unable to write to %s. Check write-access of a file.', $controllerPath));
         } else {
             throw new BuilderException(sprintf('The Controller %s already exists.', $name));
         }
     }
     if (!@file_put_contents($controllerPath, $code)) {
         throw new BuilderException(sprintf('Unable to write to %s.', $controllerPath));
     }
     if ($this->isConsole()) {
         $this->_notifySuccess(sprintf('Controller "%s" was successfully created.', $name));
     }
     return $className . 'Controller.php';
 }
예제 #22
0
 /**
  * Generate models
  */
 public function createAction()
 {
     if ($this->request->isPost()) {
         $force = $this->request->getPost('force', 'int');
         $schema = $this->request->getPost('schema');
         $directory = $this->request->getPost('directory');
         $namespace = $this->request->getPost('namespace');
         $tableName = $this->request->getPost('tableName');
         $genSettersGetters = $this->request->getPost('genSettersGetters', 'int');
         $foreignKeys = $this->request->getPost('foreignKeys', 'int');
         $defineRelations = $this->request->getPost('defineRelations', 'int');
         $mapcolumn = $this->request->getPost('mapcolumn', 'int');
         try {
             $component = '\\Phalcon\\Builder\\Model';
             if ($tableName == 'all') {
                 $component = '\\Phalcon\\Builder\\AllModels';
             }
             $modelBuilder = new $component(array('name' => $tableName, 'force' => $force, 'modelsDir' => $this->modelsDir, 'directory' => $directory, 'foreignKeys' => $foreignKeys, 'defineRelations' => $defineRelations, 'genSettersGetters' => $genSettersGetters, 'namespace' => $namespace, 'schema' => $schema, 'mapColumn' => $mapcolumn));
             $modelBuilder->build();
             if ($tableName == 'all') {
                 if (($n = count($modelBuilder->exist)) > 0) {
                     $mList = implode('</strong>, <strong>', $modelBuilder->exist);
                     if ($n == 1) {
                         $notice = 'Model <strong>' . $mList . '</strong> was skipped because it already exists!';
                     } else {
                         $notice = 'Models <strong>' . $mList . '</strong> were skipped because they already exists!';
                     }
                     $this->flash->notice($notice);
                 }
             }
             if ($tableName == 'all') {
                 $this->flash->success('Models were created successfully.');
             } else {
                 $this->flash->success(sprintf('Model "%s" was created successfully', Utils::camelize(str_replace('.php', '', $tableName))));
             }
         } catch (BuilderException $e) {
             $this->flash->error($e->getMessage());
         }
     }
     return $this->dispatcher->forward(array('controller' => 'models', 'action' => 'list'));
 }
예제 #23
0
 /**
  * Generate Scaffold
  */
 public function generateAction()
 {
     if ($this->request->isPost()) {
         $schema = $this->request->getPost('schema', 'string');
         $tableName = $this->request->getPost('tableName', 'string');
         $version = $this->request->getPost('version', 'string');
         $templateEngine = $this->request->getPost('templateEngine');
         $force = $this->request->getPost('force', 'int');
         $genSettersGetters = $this->request->getPost('genSettersGetters', 'int');
         $directory = $this->request->getPost('directory');
         $modelsNamespace = $this->request->getPost('modelsNamespace', 'trim');
         try {
             $scaffoldBuilder = new Scaffold(array('name' => $tableName, 'schema' => $schema, 'force' => $force, 'genSettersGetters' => $genSettersGetters, 'directory' => $directory, 'templatePath' => TEMPLATE_PATH, 'templateEngine' => $templateEngine, 'modelsNamespace' => $modelsNamespace));
             $scaffoldBuilder->build();
             $this->flash->success(sprintf('Scaffold for table "%s" was generated successfully', Utils::camelize($tableName)));
             return $this->dispatcher->forward(array('controller' => 'scaffold', 'action' => 'index'));
         } catch (BuilderException $e) {
             $this->flash->error($e->getMessage());
         }
     }
     return $this->dispatcher->forward(array('controller' => 'scaffold', 'action' => 'index'));
 }
예제 #24
0
 public function build()
 {
     if (!$this->options->contains('name')) {
         throw new BuilderException('You must specify the table name');
     }
     if ($this->options->contains('directory')) {
         $this->path->setRootPath($this->options->get('directory'));
     }
     $config = $this->getConfig();
     if (!($modelsDir = $this->options->get('modelsDir'))) {
         if (!isset($config->application->modelsDir)) {
             throw new BuilderException("Builder doesn't know where is the models directory.");
         }
         $modelsDir = $config->application->modelsDir;
     }
     $modelsDir = rtrim($modelsDir, '/\\') . DIRECTORY_SEPARATOR;
     $modelPath = $modelsDir;
     if (false == $this->isAbsolutePath($modelsDir)) {
         $modelPath = $this->path->getRootPath($modelsDir);
     }
     $methodRawCode = array();
     $className = $this->options->get('className');
     $modelPath .= $className . '.php';
     if (file_exists($modelPath) && !$this->options->contains('force')) {
         throw new BuilderException(sprintf('The model file "%s.php" already exists in models dir', $className));
     }
     if (!isset($config->database)) {
         throw new BuilderException('Database configuration cannot be loaded from your config file.');
     }
     if (!isset($config->database->adapter)) {
         throw new BuilderException("Adapter was not found in the config. " . "Please specify a config variable [database][adapter]");
     }
     $namespace = '';
     if ($this->options->contains('namespace') && $this->checkNamespace($this->options->get('namespace'))) {
         $namespace = 'namespace ' . $this->options->get('namespace') . ';' . PHP_EOL . PHP_EOL;
     }
     $genDocMethods = $this->options->get('genDocMethods', false);
     $useSettersGetters = $this->options->get('genSettersGetters', false);
     $adapter = $config->database->adapter;
     $this->isSupportedAdapter($adapter);
     $adapter = 'Mysql';
     if (isset($config->database->adapter)) {
         $adapter = $config->database->adapter;
     }
     if (is_object($config->database)) {
         $configArray = $config->database->toArray();
     } else {
         $configArray = $config->database;
     }
     // An array for use statements
     $uses = array();
     $adapterName = 'Phalcon\\Db\\Adapter\\Pdo\\' . $adapter;
     unset($configArray['adapter']);
     /** @var \Phalcon\Db\Adapter\Pdo $db */
     $db = new $adapterName($configArray);
     $initialize = array();
     if ($this->options->contains('schema')) {
         $schema = $this->options->get('schema');
         if ($schema != $config->database->dbname) {
             $initialize[] = $this->snippet->getThisMethod('setSchema', $schema);
         }
     } elseif ($adapter == 'Postgresql') {
         $schema = 'public';
         $initialize[] = $initialize[] = $this->snippet->getThisMethod('setSchema', $schema);
     } else {
         $schema = $config->database->dbname;
     }
     $table = $this->options->get('name');
     if ($this->options->get('fileName') != $this->options->get('name')) {
         $initialize[] = $this->snippet->getThisMethod('setSource', '\'' . $table . '\'');
     }
     if (!$db->tableExists($table, $schema)) {
         throw new BuilderException(sprintf('Table "%s" does not exist.', $table));
     }
     $fields = $db->describeColumns($table, $schema);
     foreach ($db->listTables() as $tableName) {
         foreach ($db->describeReferences($tableName, $schema) as $reference) {
             if ($reference->getReferencedTable() != $this->options->get('name')) {
                 continue;
             }
             $entityNamespace = '';
             if ($this->options->contains('namespace')) {
                 $entityNamespace = $this->options->get('namespace') . "\\";
             }
             $refColumns = $reference->getReferencedColumns();
             $columns = $reference->getColumns();
             $initialize[] = $this->snippet->getRelation('hasMany', $refColumns[0], $entityNamespace . Utils::camelize($tableName), $columns[0], "array('alias' => '" . Utils::camelize($tableName) . "')");
         }
     }
     foreach ($db->describeReferences($this->options->get('name'), $schema) as $reference) {
         $entityNamespace = '';
         if ($this->options->contains('namespace')) {
             $entityNamespace = $this->options->get('namespace') . "\\";
         }
         $refColumns = $reference->getReferencedColumns();
         $columns = $reference->getColumns();
         $initialize[] = $this->snippet->getRelation('belongsTo', $columns[0], $entityNamespace . Utils::camelize($reference->getReferencedTable()), $refColumns[0], "array('alias' => '" . Utils::camelize($reference->getReferencedTable()) . "')");
     }
     if ($this->options->has('hasMany')) {
         if (count($this->options->get('hasMany'))) {
             foreach ($this->options->get('hasMany') as $relation) {
                 if (!is_string($relation['fields'])) {
                     continue;
                 }
                 $entityName = $relation['camelizedName'];
                 $entityNamespace = '';
                 if ($this->options->contains('namespace')) {
                     $entityNamespace = $this->options->get('namespace') . "\\";
                     $relation['options']['alias'] = $entityName;
                 }
                 $initialize[] = $this->snippet->getRelation('hasMany', $relation['fields'], $entityNamespace . $entityName, $relation['relationFields'], $this->snippet->getRelationOptions(isset($relation['options']) ? $relation["options"]->toArray() : null));
             }
         }
     }
     if ($this->options->has('belongsTo')) {
         if (count($this->options->get('belongsTo'))) {
             foreach ($this->options->get('belongsTo') as $relation) {
                 if (!is_string($relation['fields'])) {
                     continue;
                 }
                 $entityName = Utils::camelize($relation['referencedModel']);
                 $entityNamespace = '';
                 if ($this->options->contains('namespace')) {
                     $entityNamespace = $this->options->get('namespace') . "\\";
                     $relation['options']['alias'] = $entityName;
                 }
                 $initialize[] = $this->snippet->getRelation('belongsTo', $relation['fields'], $entityNamespace . $entityName, $relation['relationFields'], $this->snippet->getRelationOptions(isset($relation['options']) ? $relation["options"]->toArray() : null));
             }
         }
     }
     $alreadyInitialized = false;
     $alreadyValidations = false;
     $alreadyFind = false;
     $alreadyFindFirst = false;
     $alreadyColumnMapped = false;
     $alreadyGetSourced = false;
     if (file_exists($modelPath)) {
         try {
             $possibleMethods = array();
             if ($useSettersGetters) {
                 foreach ($fields as $field) {
                     /** @var \Phalcon\Db\Column $field */
                     $methodName = Utils::camelize($field->getName());
                     $possibleMethods['set' . $methodName] = true;
                     $possibleMethods['get' . $methodName] = true;
                 }
             }
             $possibleMethods['getSource'] = true;
             require $modelPath;
             $linesCode = file($modelPath);
             $fullClassName = $this->options->get('className');
             if ($this->options->contains('namespace')) {
                 $fullClassName = $this->options->get('namespace') . '\\' . $fullClassName;
             }
             $reflection = new ReflectionClass($fullClassName);
             foreach ($reflection->getMethods() as $method) {
                 if ($method->getDeclaringClass()->getName() != $fullClassName) {
                     continue;
                 }
                 $methodName = $method->getName();
                 if (isset($possibleMethods[$methodName])) {
                     continue;
                 }
                 $indent = PHP_EOL;
                 if ($method->getDocComment()) {
                     $firstLine = $linesCode[$method->getStartLine() - 1];
                     preg_match('#^\\s+#', $firstLine, $matches);
                     if (isset($matches[0])) {
                         $indent .= $matches[0];
                     }
                 }
                 $methodDeclaration = join('', array_slice($linesCode, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1));
                 $methodRawCode[$methodName] = $indent . $method->getDocComment() . PHP_EOL . $methodDeclaration;
                 switch ($methodName) {
                     case 'initialize':
                         $alreadyInitialized = true;
                         break;
                     case 'validation':
                         $alreadyValidations = true;
                         break;
                     case 'find':
                         $alreadyFind = true;
                         break;
                     case 'findFirst':
                         $alreadyFindFirst = true;
                         break;
                     case 'columnMap':
                         $alreadyColumnMapped = true;
                         break;
                     case 'getSource':
                         $alreadyGetSourced = true;
                         break;
                 }
             }
         } catch (ReflectionException $e) {
         }
     }
     $validations = array();
     foreach ($fields as $field) {
         if ($field->getType() === Column::TYPE_CHAR) {
             $domain = array();
             if (preg_match('/\\((.*)\\)/', $field->getType(), $matches)) {
                 foreach (explode(',', $matches[1]) as $item) {
                     $domain[] = $item;
                 }
             }
             if (count($domain)) {
                 $varItems = join(', ', $domain);
                 $validations[] = $this->snippet->getValidateInclusion($field->getName(), $varItems);
             }
         }
         if ($field->getName() == 'email') {
             $validations[] = $this->snippet->getValidateEmail($field->getName());
             $uses[] = $this->snippet->getUseAs('Phalcon\\Mvc\\Model\\Validator\\Email', 'Email');
         }
     }
     if (count($validations)) {
         $validations[] = $this->snippet->getValidationFailed();
     }
     // Check if there has been an extender class
     $extends = $this->options->get('extends', '\\Phalcon\\Mvc\\Model');
     // Check if there have been any excluded fields
     $exclude = array();
     if ($this->options->contains('excludeFields')) {
         $keys = explode(',', $this->options->get('excludeFields'));
         if (count($keys) > 0) {
             foreach ($keys as $key) {
                 $exclude[trim($key)] = '';
             }
         }
     }
     $attributes = array();
     $setters = array();
     $getters = array();
     foreach ($fields as $field) {
         $type = $this->getPHPType($field->getType());
         if ($useSettersGetters) {
             if (!array_key_exists(strtolower($field->getName()), $exclude)) {
                 $attributes[] = $this->snippet->getAttributes($type, 'protected', $field->getName());
                 $setterName = Utils::camelize($field->getName());
                 $setters[] = $this->snippet->getSetter($field->getName(), $type, $setterName);
                 if (isset($this->_typeMap[$type])) {
                     $getters[] = $this->snippet->getGetterMap($field->getName(), $type, $setterName, $this->_typeMap[$type]);
                 } else {
                     $getters[] = $this->snippet->getGetter($field->getName(), $type, $setterName);
                 }
             }
         } else {
             $attributes[] = $this->snippet->getAttributes($type, 'public', $field->getName());
         }
     }
     $validationsCode = '';
     if ($alreadyValidations == false && count($validations) > 0) {
         $validationsCode = $this->snippet->getValidationsMethod($validations);
     }
     $initCode = '';
     if ($alreadyInitialized == false && count($initialize) > 0) {
         $initCode = $this->snippet->getInitialize($initialize);
     }
     $license = '';
     if (file_exists('license.txt')) {
         $license = trim(file_get_contents('license.txt')) . PHP_EOL . PHP_EOL;
     }
     if (false == $alreadyGetSourced) {
         $methodRawCode[] = $this->snippet->getModelSource($this->options->get('name'));
     }
     if (false == $alreadyFind) {
         $methodRawCode[] = $this->snippet->getModelFind($className);
     }
     if (false == $alreadyFindFirst) {
         $methodRawCode[] = $this->snippet->getModelFindFirst($className);
     }
     $content = join('', $attributes);
     if ($useSettersGetters) {
         $content .= join('', $setters) . join('', $getters);
     }
     $content .= $validationsCode . $initCode;
     foreach ($methodRawCode as $methodCode) {
         $content .= $methodCode;
     }
     $classDoc = '';
     if ($genDocMethods) {
         $classDoc = $this->snippet->getClassDoc($className, $namespace);
     }
     if ($this->options->contains('mapColumn') && false == $alreadyColumnMapped) {
         $content .= $this->snippet->getColumnMap($fields);
     }
     $useDefinition = '';
     if (!empty($uses)) {
         $useDefinition = join('', $uses) . PHP_EOL . PHP_EOL;
     }
     $abstract = $this->options->contains('abstract') ? 'abstract ' : '';
     $code = $this->snippet->getClass($namespace, $useDefinition, $classDoc, $abstract, $className, $extends, $content, $license);
     if (file_exists($modelPath) && !is_writable($modelPath)) {
         throw new BuilderException(sprintf('Unable to write to %s. Check write-access of a file.', $modelPath));
     }
     if (!file_put_contents($modelPath, $code)) {
         throw new BuilderException(sprintf('Unable to write to %s', $modelPath));
     }
     if ($this->isConsole()) {
         $msgSuccess = ($this->options->contains('abstract') ? 'Abstract ' : '') . 'Model "%s" was successfully created.';
         $this->_notifySuccess(sprintf($msgSuccess, Utils::camelize($this->options->get('name'))));
     }
 }
예제 #25
0
 /**
  * @throws \Phalcon\Builder\BuilderException
  */
 private function _makeViewSearchVolt()
 {
     $dirPath = $this->options->viewsDir . $this->options->fileName;
     if (is_dir($dirPath) == false) {
         mkdir($dirPath);
     }
     $viewPath = $dirPath . DIRECTORY_SEPARATOR . 'search.volt';
     if (file_exists($viewPath)) {
         if (!$this->options->contains('force')) {
             return;
         }
     }
     $templatePath = $this->options->templatePath . '/scaffold/no-forms/views/search.volt';
     if (!file_exists($templatePath)) {
         throw new BuilderException("Template '" . $templatePath . "' does not exist");
     }
     $headerCode = '';
     foreach ($this->options->attributes as $attribute) {
         $headerCode .= "\t\t\t" . '<th>' . $this->_getPossibleLabel($attribute) . '</th>' . PHP_EOL;
     }
     $rowCode = '';
     $this->options->offsetSet('allReferences', array_merge($this->options->autocompleteFields->toArray(), $this->options->selectDefinition->toArray()));
     foreach ($this->options->dataTypes as $fieldName => $dataType) {
         $rowCode .= "\t\t\t" . '<td>{{ ';
         if (!isset($this->options->allReferences[$fieldName])) {
             if ($this->options->contains('genSettersGetters')) {
                 $rowCode .= $this->options->singular . '.get' . Text::camelize($fieldName) . '()';
             } else {
                 $rowCode .= $this->options->singular . '.' . $fieldName;
             }
         } else {
             $detailField = ucfirst($this->options->allReferences[$fieldName]['detail']);
             $rowCode .= $this->options->singular . '.get' . $this->options->allReferences[$fieldName]['tableName'] . '().get' . $detailField . '()';
         }
         $rowCode .= ' }}</td>' . PHP_EOL;
     }
     $idField = $this->options->attributes[0];
     if ($this->options->contains('genSettersGetters')) {
         $idField = 'get' . Text::camelize($this->options->attributes[0]) . '()';
     }
     $code = file_get_contents($templatePath);
     $code = str_replace('$plural$', $this->options->plural, $code);
     $code = str_replace('$headerColumns$', $headerCode, $code);
     $code = str_replace('$rowColumns$', $rowCode, $code);
     $code = str_replace('$singularVar$', $this->options->singular, $code);
     $code = str_replace('$pk$', $idField, $code);
     if ($this->isConsole()) {
         echo $viewPath, PHP_EOL;
     }
     $code = str_replace("\t", "    ", $code);
     file_put_contents($viewPath, $code);
 }
예제 #26
0
 public function build()
 {
     $options = $this->_options;
     $path = '';
     if (isset($this->_options['directory'])) {
         if ($this->_options['directory']) {
             $path = $this->_options['directory'] . '/';
         }
     }
     $name = $options['name'];
     $config = $this->_getConfig($path);
     if (!isset($config->database->adapter)) {
         throw new BuilderException("Adapter was not found in the config. Please specify a config varaible [database][adapter]");
     }
     $adapter = ucfirst($config->database->adapter);
     $this->isSupportedAdapter($adapter);
     $di = new \Phalcon\DI\FactoryDefault();
     $di->set('db', function () use($adapter, $config) {
         $adapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $adapter;
         $connection = new $adapter(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->name));
         return $connection;
     });
     if (isset($config->application->modelsDir)) {
         $options['modelsDir'] = $path . $config->application->modelsDir;
     } else {
         throw new BuilderException("The builder is unable to know where is the views directory");
     }
     if (isset($config->application->controllersDir)) {
         $options['controllersDir'] = $path . $config->application->controllersDir;
     } else {
         throw new BuilderException("The builder is unable to know where is the controllers directory");
     }
     if (isset($config->application->viewsDir)) {
         $options['viewsDir'] = $path . $config->application->viewsDir;
     } else {
         throw new BuilderException("The builder is unable to know where is the views directory");
     }
     $options['manager'] = $di->getShared('modelsManager');
     $options['className'] = Text::camelize($options['name']);
     $options['fileName'] = Text::uncamelize($options['className']);
     $modelBuilder = new \Phalcon\Builder\Model(array('name' => $name, 'schema' => $options['schema'], 'className' => $options['className'], 'fileName' => $options['fileName'], 'genSettersGetters' => $options['genSettersGetters'], 'directory' => $options['directory'], 'force' => $options['force']));
     $modelBuilder->build();
     $modelClass = Text::camelize($name);
     if (!class_exists($modelClass)) {
         require $config->application->modelsDir . '/' . $modelClass . '.php';
     }
     $entity = new $modelClass();
     $metaData = $di->getShared('modelsMetadata');
     $attributes = $metaData->getAttributes($entity);
     $dataTypes = $metaData->getDataTypes($entity);
     $identityField = $metaData->getIdentityField($entity);
     $primaryKeys = $metaData->getPrimaryKeyAttributes($entity);
     $setParams = array();
     $selectDefinition = array();
     $relationField = '';
     $single = $name;
     $options['name'] = strtolower(Text::camelize($single));
     $options['plural'] = str_replace('_', ' ', $single);
     $options['single'] = str_replace('_', ' ', $single);
     $options['entity'] = $entity;
     $options['theSingle'] = $single;
     $options['singleVar'] = $single;
     $options['setParams'] = $setParams;
     $options['attributes'] = $attributes;
     $options['dataTypes'] = $dataTypes;
     $options['primaryKeys'] = $primaryKeys;
     $options['identityField'] = $identityField;
     $options['relationField'] = $relationField;
     $options['selectDefinition'] = $selectDefinition;
     $options['autocompleteFields'] = array();
     $options['belongsToDefinitions'] = array();
     //Build Controller
     $this->_makeController($path, $options);
     //View layouts
     $this->_makeLayouts($path, $options);
     //View index.phtml
     $this->_makeViewIndex($path, $options);
     //View search.phtml
     $this->_makeViewSearch($path, $options);
     //View new.phtml
     $this->_makeViewNew($path, $options);
     //View edit.phtml
     $this->_makeViewEdit($path, $options);
     return true;
 }
예제 #27
0
 /**
  * Builds a controller
  *
  * @return string
  * @throws \Phalcon\Builder\Exception
  */
 public function build()
 {
     $path = '';
     if (isset($this->_options['directory'])) {
         if ($this->_options['directory']) {
             $path = $this->_options['directory'] . '/';
         }
     }
     if (isset($this->_options['namespace'])) {
         $namespace = 'namespace ' . $this->_options['namespace'] . ';' . PHP_EOL . PHP_EOL;
     } else {
         $namespace = '';
     }
     if (isset($this->_options['baseClass'])) {
         $baseClass = $this->_options['baseClass'];
     } else {
         $baseClass = '\\Phalcon\\Mvc\\Controller';
     }
     if (!isset($this->_options['controllersDir'])) {
         $config = $this->_getConfig($path);
         if (!isset($config->application->controllersDir)) {
             throw new BuilderException("Builder doesn't knows where is the controllers directory");
         }
         $controllersDir = $config->application->controllersDir;
     } else {
         $controllersDir = $this->_options['controllersDir'];
     }
     if ($this->isAbsolutePath($controllersDir) == false) {
         $controllerPath = $path . "public/" . $controllersDir;
     } else {
         $controllerPath = $controllersDir;
     }
     $name = $this->_options['name'];
     if (!$name) {
         throw new BuilderException("The controller name is required");
     }
     $className = Utils::camelize($name);
     $controllerPath .= $className . "Controller.php";
     $code = "<?php\n\n" . $namespace . "class " . $className . "Controller extends " . $baseClass . "\n{\n\n\tpublic function indexAction()\n\t{\n\n\t}\n\n}\n\n";
     $code = str_replace("\t", "    ", $code);
     if (!file_exists($controllerPath) || $this->_options['force'] == true) {
         file_put_contents($controllerPath, $code);
     } else {
         throw new BuilderException("The Controller '{$name}' already exists");
     }
     $this->_notifySuccess('Controller "' . $name . '" was successfully created.');
     return $className . 'Controller.php';
 }
예제 #28
0
 public function build()
 {
     $getSource = "\n    public function getSource()\n    {\n        return '%s';\n    }\n";
     $templateThis = "        \$this->%s(%s);" . PHP_EOL;
     $templateRelation = "        \$this->%s('%s', '%s', '%s', %s);" . PHP_EOL;
     $templateSetter = "\n    /**\n     * Method to set the value of field %s\n     *\n     * @param %s \$%s\n     * @return \$this\n     */\n    public function set%s(\$%s)\n    {\n        \$this->%s = \$%s;\n\n        return \$this;\n    }\n";
     $templateValidateInclusion = "\n        \$this->validate(\n            new InclusionIn(\n                array(\n                    'field'    => '%s',\n                    'domain'   => array(%s),\n                    'required' => true,\n                )\n            )\n        );";
     $templateValidateEmail = "\n        \$this->validate(\n            new Email(\n                array(\n                    'field'    => '%s',\n                    'required' => true,\n                )\n            )\n        );";
     $templateValidationFailed = "\n        if (\$this->validationHasFailed() == true) {\n            return false;\n        }";
     $templateAttributes = "\n    /**\n     *\n     * @var %s\n     */\n    %s \$%s;\n";
     $templateGetterMap = "\n    /**\n     * Returns the value of field %s\n     *\n     * @return %s\n     */\n    public function get%s()\n    {\n        if (\$this->%s) {\n            return new %s(\$this->%s);\n        } else {\n           return null;\n        }\n    }\n";
     $templateGetter = "\n    /**\n     * Returns the value of field %s\n     *\n     * @return %s\n     */\n    public function get%s()\n    {\n        return \$this->%s;\n    }\n";
     $templateValidations = "\n    /**\n     * Validations and business logic\n     */\n    public function validation()\n    {\n%s\n    }\n";
     $templateInitialize = "\n    /**\n     * Initialize method for model.\n     */\n    public function initialize()\n    {\n%s\n    }\n";
     $templateFind = "\n    /**\n     * @return %s[]\n     */\n    public static function find(\$parameters = array())\n    {\n        return parent::find(\$parameters);\n    }\n\n    /**\n     * @return %s\n     */\n    public static function findFirst(\$parameters = array())\n    {\n        return parent::findFirst(\$parameters);\n    }\n";
     $templateUse = 'use %s;';
     $templateUseAs = 'use %s as %s;';
     $templateCode = "<?php\n\n%s%s%sclass %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'] . '/';
         }
     } else {
         $path = '.';
     }
     var_dump($this->_getConfig($path));
     $config = $this->_getConfig($path);
     if (!isset($this->_options['modelsDir'])) {
         if (!isset($config->application->modelsDir) || !file_exists('models_tmp')) {
             throw new BuilderException("Builder doesn't knows where is the models directory");
         }
         if (isset($config->application)) {
             $modelsDir = $config->application->modelsDir;
         } else {
             $modelsDir = 'models_tmp';
         }
     } else {
         $modelsDir = $this->_options['modelsDir'];
     }
     $modelsDir = rtrim(rtrim($modelsDir, '/'), '\\') . DIRECTORY_SEPARATOR;
     if ($this->isAbsolutePath($modelsDir) == false) {
         $modelPath = $path . 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;
     }
     // An array for use statements
     $uses = array();
     $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'];
                     if (isset($this->_options['namespace'])) {
                         $entityNamespace = "{$this->_options['namespace']}\\";
                         $relation['options']['alias'] = $entityName;
                     } else {
                         $entityNamespace = '';
                     }
                     $initialize[] = sprintf($templateRelation, 'hasMany', $relation['fields'], $entityNamespace . $entityName, $relation['relationFields'], $this->_buildRelationOptions(isset($relation['options']) ? $relation["options"] : NULL));
                 }
             }
         }
     }
     if (isset($this->_options['belongsTo'])) {
         if (count($this->_options['belongsTo'])) {
             foreach ($this->_options['belongsTo'] as $relation) {
                 if (is_string($relation['fields'])) {
                     $entityName = $relation['referencedModel'];
                     if (isset($this->_options['namespace'])) {
                         $entityNamespace = "{$this->_options['namespace']}\\";
                         $relation['options']['alias'] = $entityName;
                     } else {
                         $entityNamespace = '';
                     }
                     $initialize[] = sprintf($templateRelation, 'belongsTo', $relation['fields'], $entityNamespace . $entityName, $relation['relationFields'], $this->_buildRelationOptions(isset($relation['options']) ? $relation["options"] : NULL));
                 }
             }
         }
     }
     $alreadyInitialized = false;
     $alreadyValidations = false;
     if (file_exists($modelPath)) {
         try {
             $possibleMethods = array();
             if ($useSettersGetters) {
                 foreach ($fields as $field) {
                     $methodName = Utils::camelize($field->getName());
                     $possibleMethods['set' . $methodName] = true;
                     $possibleMethods['get' . $methodName] = true;
                 }
             }
             require $modelPath;
             $linesCode = file($modelPath);
             $fullClassName = $this->_options['className'];
             if (isset($this->_options['namespace'])) {
                 $fullClassName = $this->_options['namespace'] . '\\' . $fullClassName;
             }
             $reflection = new \ReflectionClass($fullClassName);
             foreach ($reflection->getMethods() as $method) {
                 if ($method->getDeclaringClass()->getName() == $fullClassName) {
                     $methodName = $method->getName();
                     if (!isset($possibleMethods[$methodName])) {
                         $methodRawCode[$methodName] = join('', array_slice($linesCode, $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1));
                     } else {
                         continue;
                     }
                     if ($methodName == 'initialize') {
                         $alreadyInitialized = true;
                     } else {
                         if ($methodName == 'validation') {
                             $alreadyValidations = true;
                         }
                     }
                 }
             }
         } catch (\ReflectionException $e) {
         }
     }
     $validations = array();
     foreach ($fields as $field) {
         if ($field->getType() === Column::TYPE_CHAR) {
             $domain = array();
             if (preg_match('/\\((.*)\\)/', $field->getType(), $matches)) {
                 foreach (explode(',', $matches[1]) as $item) {
                     $domain[] = $item;
                 }
             }
             if (count($domain)) {
                 $varItems = join(', ', $domain);
                 $validations[] = sprintf($templateValidateInclusion, $field->getName(), $varItems);
             }
         }
         if ($field->getName() == 'email') {
             $validations[] = sprintf($templateValidateEmail, $field->getName());
             $uses[] = sprintf($templateUseAs, 'Phalcon\\Mvc\\Model\\Validator\\Email', 'Email');
         }
     }
     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, rtrim(join('', $initialize)));
         } else {
             $initCode = '';
         }
     } else {
         $initCode = '';
     }
     $license = '';
     if (file_exists('license.txt')) {
         $license = trim(file_get_contents('license.txt')) . PHP_EOL . PHP_EOL;
     }
     $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);
     }
     $str_use = '';
     if (!empty($uses)) {
         $str_use = implode(PHP_EOL, $uses) . PHP_EOL . PHP_EOL;
     }
     $code = sprintf($templateCode, $license, $namespace, $str_use, $className, $extends, $content);
     if (!@file_put_contents($modelPath, $code)) {
         throw new BuilderException("Unable to write to '{$modelPath}'");
     }
     if ($this->isConsole()) {
         $this->_notifySuccess('Model "' . $this->_options['name'] . '" was successfully created.');
     }
 }
예제 #29
0
 public function __set($name, $value)
 {
     $methodName = 'set' . Text::camelize($name);
     $this->_attributes[$name] = method_exists($this, $methodName) ? $this->{$methodName}($value) : $this->castAttribute($name, $value);
 }
예제 #30
0
 /**
  * Migrate single file
  *
  * @param $version
  * @param $filePath
  *
  * @throws Exception
  */
 public static function migrateFile($version, $filePath)
 {
     if (file_exists($filePath)) {
         $fileName = basename($filePath);
         $classVersion = preg_replace('/[^0-9A-Za-z]/', '', $version);
         $className = Text::camelize(str_replace('.php', '', $fileName)) . 'Migration_' . $classVersion;
         require_once $filePath;
         if (!class_exists($className)) {
             throw new Exception('Migration class cannot be found ' . $className . ' at ' . $filePath);
         }
         $migration = new $className();
         if (method_exists($migration, 'up')) {
             $migration->up();
             if (method_exists($migration, 'afterUp')) {
                 $migration->afterUp();
             }
         }
     }
 }