public static function getRecursiveObjIdsArrForClassName($model_class_name, $parent_id_field_name, $filters_arr, $order_by = '', $parent_id = null, $depth = 0) { \OLOG\CheckClassInterfaces::exceptionIfClassNotImplementsInterface($model_class_name, \OLOG\Model\InterfaceLoad::class); $db_table_name = $model_class_name::DB_TABLE_NAME; $db_id = $model_class_name::DB_ID; $db_id_field_name = CRUDFieldsAccess::getIdFieldName($model_class_name); $query_param_values_arr = array(); $where = ' 1 = 1 '; if (is_null($parent_id)) { $where .= ' and ' . $parent_id_field_name . ' is null '; } else { $where .= ' and ' . $parent_id_field_name . ' = ? '; $query_param_values_arr[] = $parent_id; } /** @var InterfaceCRUDTableFilter2 $filter_obj */ foreach ($filters_arr as $filter_obj) { Assert::assert($filter_obj instanceof InterfaceCRUDTableFilter2); list($filter_sql_condition, $filter_placeholder_values_arr) = $filter_obj->sqlConditionAndPlaceholderValue(); if ($filter_sql_condition != '') { $where .= ' and ' . $filter_sql_condition; } $query_param_values_arr = array_merge($query_param_values_arr, $filter_placeholder_values_arr); } if ($order_by == '') { $order_by = $db_id_field_name; } $obj_ids_arr = \OLOG\DB\DBWrapper::readColumn($db_id, "select " . $db_id_field_name . " from " . $db_table_name . ' where ' . $where . ' order by ' . $order_by, $query_param_values_arr); $output_arr = []; foreach ($obj_ids_arr as $fetched_obj_id) { $output_arr[] = ['id' => $fetched_obj_id, 'depth' => $depth]; $output_arr = array_merge($output_arr, self::getRecursiveObjIdsArrForClassName($model_class_name, $parent_id_field_name, $filters_arr, $order_by, $fetched_obj_id, $depth + 1)); } return $output_arr; }
public function testAssert() { \OLOG\Assert::assert(true); $this->expectException('Exception'); $this->expectExceptionMessage('Assertion failed'); \OLOG\Assert::assert(false); }
public static function factory($class_name, $id_to_load, $exception_if_not_loaded = true) { $obj = \OLOG\Model\Factory::createAndLoadObject($class_name, $id_to_load); if ($exception_if_not_loaded) { \OLOG\Assert::assert($obj); } return $obj; }
/** * Loads file. * PHPClassFile constructor. * @param $model_file_path */ public function __construct($model_file_path) { $this->class_file_path = $model_file_path; $this->class_file_text = file_get_contents($this->class_file_path); Assert::assert($this->class_file_text); // TODO: better check? $this->extractClassName(); $this->extractClassNamespace(); }
public static function getRequiredPostValue($key) { $value = ''; if (array_key_exists($key, $_POST)) { $value = $_POST[$key]; } \OLOG\Assert::assert($value != '', 'Missing required POST field ' . $key); // TODO: library used while not mentioned in config return $value; }
public static function getObjectFieldValue($obj, $field_name) { $obj_class_name = get_class($obj); $reflect = new \ReflectionClass($obj_class_name); $field_prop_obj = null; foreach ($reflect->getProperties() as $prop_obj) { if ($prop_obj->getName() == $field_name) { $field_prop_obj = $prop_obj; } } \OLOG\Assert::assert($field_prop_obj, 'Field "' . $field_name . '" not found in object. Object class: "' . $obj_class_name . '"'); $field_prop_obj->setAccessible(true); return $field_prop_obj->getValue($obj); }
public function html($obj) { Assert::assert($obj); $o = ''; $o .= '<form style="display: inline;" method="post" action="' . \OLOG\Url::getCurrentUrl() . '">'; $o .= Operations::operationCodeHiddenField(CRUDTable::OPERATION_DELETE_MODEL); $o .= '<input type="hidden" name="' . self::FIELD_CLASS_NAME . '" value="' . Sanitize::sanitizeAttrValue(get_class($obj)) . '">'; $o .= '<input type="hidden" name="' . self::FIELD_OBJECT_ID . '" value="' . Sanitize::sanitizeAttrValue(CRUDFieldsAccess::getObjId($obj)) . '">'; if ($this->redirect_after_delete_url != '') { $o .= '<input type="hidden" name="' . self::FIELD_REDIRECT_AFTER_DELETE_URL . '" value="' . Sanitize::sanitizeAttrValue($this->redirect_after_delete_url) . '">'; } $o .= '<button class="' . $this->button_class_str . '" type="submit" onclick="return window.confirm(\'Delete?\');">' . $this->button_text . '</button>'; $o .= '</form>'; return $o; }
public function html($obj) { Assert::assert($obj); $title_field_name = $this->getTitleFieldName(); $obj_title = CRUDFieldsAccess::getObjectFieldValue($obj, $title_field_name); $id_field_name = $this->getIdFieldName(); if ($id_field_name == '') { $id = CRUDFieldsAccess::getObjId($obj); } else { $id = CRUDFieldsAccess::getObjectFieldValue($obj, $id_field_name); } $o = ''; $o .= '<button class="btn btn-xs btn-default js-ajax-form-select" type="submit" data-id="' . Sanitize::sanitizeAttrValue($id) . '" data-title="' . Sanitize::sanitizeAttrValue($obj_title) . '">Выбор</button>'; return $o; }
public static function getReplacement($obj, $obj_field_name) { \OLOG\Assert::assert($obj); $matches = []; if (preg_match('@^(\\w+)\\(\\)$@', $obj_field_name, $matches)) { // имя поля заканчивается скобками - значит это имя метода $method_name = $matches[1]; Assert::assert(method_exists($obj, $method_name)); $replacement = call_user_func([$obj, $method_name]); } else { $replacement = CRUDFieldsAccess::getObjectFieldValue($obj, $obj_field_name); } if (is_null($replacement)) { $replacement = self::NULL_STRING; } return $replacement; }
/** * @param $obj InterfaceWeight * @return string */ public function html($obj) { Assert::assert($obj); $o = ''; $o .= '<form style="display: inline;" method="post" action="' . \OLOG\Url::getCurrentUrl() . '">'; $o .= Operations::operationCodeHiddenField(CRUDTable::OPERATION_SWAP_MODEL_WEIGHT); $o .= '<input type="hidden" name="' . self::FORMFIELD_CONTEXT_FIELDS_NAME . '" value="' . Sanitize::sanitizeAttrValue(implode(',', array_keys($this->context_fields_arr))) . '">'; foreach ($this->context_fields_arr as $context_field_name => $context_field_value) { $context_field_value = CRUDCompiler::compile($context_field_value, ['this' => $obj]); $o .= NullablePostFields::hiddenFieldHtml($context_field_name, $context_field_value); } $o .= '<input type="hidden" name="_class_name" value="' . Sanitize::sanitizeAttrValue(get_class($obj)) . '">'; $o .= '<input type="hidden" name="_id" value="' . Sanitize::sanitizeAttrValue(CRUDFieldsAccess::getObjId($obj)) . '">'; $o .= '<button class="' . $this->button_class_str . '" type="submit">' . $this->button_text . '</button>'; $o .= '</form>'; return $o; }
public static function getMcConnectionObj() { static $memcache = NULL; if (isset($memcache)) { return $memcache; } //$memcache_servers = \OLOG\ConfWrapper::value(\OLOG\Model\ModelConstants::MODULE_CONFIG_ROOT_KEY . '.memcache_servers'); $memcache_servers = CacheConfig::getServersObjArr(); if (!$memcache_servers) { return null; } // Memcached php extension not supported - slower, rare, extra features not needed /** @var \Memcache $memcache */ $memcache = new \Memcache(); /** @var MemcacheServerSettings $server_settings_obj */ foreach ($memcache_servers as $server_settings_obj) { \OLOG\Assert::assert($memcache->addServer($server_settings_obj->getHost(), $server_settings_obj->getPort())); $memcache->setCompressThreshold(5000, 0.2); } return $memcache; }
/** * @param $obj InterfaceOwner * Does not saves object - designed to be called from constructor. */ public static function assignCurrentUserAsOwnerToObj($obj) { Assert::assert($obj instanceof InterfaceOwner); Assert::assert($obj instanceof InterfaceLoad); static $__inprogress = []; $inprogress_key = FullObjectId::getFullObjectId($obj); if (array_key_exists($inprogress_key, $__inprogress)) { return; } $__inprogress[$inprogress_key] = 1; // заполняем при создании объекта if (!$obj->getId()) { $current_user_id = Auth::currentUserId(); if ($current_user_id) { $obj->setOwnerUserId($current_user_id); $current_user_obj = User::factory($current_user_id); $obj->setOwnerGroupId($current_user_obj->getPrimaryGroupId()); } } unset($__inprogress[$inprogress_key]); }
/** * @param $user_id * @param $obj InterfaceOwner * @return bool */ public static function userOwnsObj($user_id, $obj) { \OLOG\Assert::assert($obj instanceof InterfaceOwner, 'Object must implement ' . \OLOG\Auth\InterfaceOwner::class . ' interface'); $current_user_obj = User::factory($user_id); if ($current_user_obj->getHasFullAccess()) { return true; } $current_user_usertogroup_ids_arr = UserToGroup::getIdsArrForUserIdByCreatedAtDesc($user_id); $current_user_groups_ids_arr = []; foreach ($current_user_usertogroup_ids_arr as $usertogroup_id) { $usertogroup_obj = UserToGroup::factory($usertogroup_id); $current_user_groups_ids_arr[] = $usertogroup_obj->getGroupId(); } if ($obj->getOwnerUserId() == $user_id) { return true; } $obj_owner_group_id = $obj->getOwnerGroupId(); if (in_array($obj_owner_group_id, $current_user_groups_ids_arr)) { return true; } return false; }
public static function chooseModelDBIndex() { echo CliUtil::delimiter(); echo "Choose model DB index:\n"; //$db_arr = \OLOG\ConfWrapper::value(\OLOG\Model\ModelConstants::MODULE_CONFIG_ROOT_KEY . '.db'); // TODO: check not empty $db_arr = DBConfig::getDBSettingsObjArr(); Assert::assert(count($db_arr) > 0, 'No database settings found in config'); // TODO: select db by index $db_id_by_index = []; $index = 1; foreach ($db_arr as $db_id => $db_settings_obj) { echo "\t" . str_pad($index, 8, '.') . $db_id . "\n"; $db_id_by_index[$index] = $db_id; $index++; } $model_db_index = CliUtil::readStdinAnswer(); if (!array_key_exists($model_db_index, $db_id_by_index)) { throw new \Exception('Wrong index'); } self::$model_db_id = $db_id_by_index[$model_db_index]; // TODO: check db presence in config? self::generateClass(); }
public function validate($validators_arr, &$error_message = null) { foreach ($validators_arr as $validator_obj) { /** * @var $validator_obj POSTFileValidatorInterface */ \OLOG\Assert::assert($validator_obj instanceof POSTFileValidatorInterface); $validator_error_message = ''; if ($validator_obj->validate($this, $validator_error_message) === false) { $error_message = $validator_error_message; return false; } } return true; }
protected static function filtersHtml($filters_arr) { $html = ''; if ($filters_arr) { $html .= '<div class="">'; $html .= '<form class="filters-form form-horizontal">'; $html .= '<div class="row">'; /** @var InterfaceCRUDTableFilter2 $filter_obj */ foreach ($filters_arr as $filter_obj) { Assert::assert($filter_obj instanceof InterfaceCRUDTableFilter2); $html .= '<div class="col-md-12">'; $html .= '<div class="form-group">'; $html .= '<label class="col-sm-4 text-right control-label">' . $filter_obj->getTitle() . '</label>'; $html .= '<div class="col-sm-8">' . $filter_obj->getHtml() . '</div>'; $html .= '</div>'; $html .= '</div>'; } $html .= '</div>'; //$html .= '<div class="row"><div class="col-sm-8 col-sm-offset-4"><button style="width: 100%;" type="submit" class="btn btn-default">Поиск</button></div></div>'; $html .= '</form>'; $html .= '</div>'; } return $html; }
public static function render($content_html, $action_obj = null) { $page_toolbar_html = ''; // запрашиваем до начала вывода на страницу, потому что там может редирект или какая-то еще работа с хидерами if ($action_obj) { if ($action_obj instanceof \OLOG\Layouts\InterfacePageToolbarHtml) { $page_toolbar_html = $action_obj->pageToolbarHtml(); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> </head> <body> <div class="container"> <?php //$application_title = BTConfig::getApplicationTitle(); $application_title = 'Home'; $menu_items_arr = []; if ($action_obj instanceof InterfaceMenu) { $menu_items_arr = $action_obj::menuArr(); } ?> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/"><?php echo $application_title; ?> </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <?php foreach ($menu_items_arr as $menu_item_obj) { \OLOG\Assert::assert($menu_item_obj instanceof \OLOG\Layouts\MenuItem); $children_arr = $menu_item_obj->getChildrenArr(); $href = 'href="#"'; if ($menu_item_obj->getUrl()) { $href = 'href="' . Sanitize::sanitizeUrl($menu_item_obj->getUrl()) . '"'; } $icon = ''; if ($menu_item_obj->getIconClassesStr()) { $icon = '<i class="' . $menu_item_obj->getIconClassesStr() . '"></i> '; } if (count($children_arr)) { ?> <li class="dropdown"> <a <?php echo $href; ?> class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <?php echo $icon . Sanitize::sanitizeTagContent($menu_item_obj->getText()); ?> <span class="caret"></span> </a> <ul class="dropdown-menu"> <?php /** @var $child_menu_item_obj \OLOG\Layouts\MenuItem */ foreach ($children_arr as $child_menu_item_obj) { \OLOG\Assert::assert($child_menu_item_obj instanceof \OLOG\Layouts\MenuItem); $children_href = ''; if ($child_menu_item_obj->getUrl()) { $children_href = 'href="' . Sanitize::sanitizeUrl($child_menu_item_obj->getUrl()) . '"'; } $children_icon = ''; if ($child_menu_item_obj->getIconClassesStr()) { $children_icon = '<i class="' . $child_menu_item_obj->getIconClassesStr() . '"></i> '; } ?> <li> <a <?php echo $children_href; ?> ><?php echo $children_icon . Sanitize::sanitizeTagContent($child_menu_item_obj->getText()); ?> </a> </li> <?php } ?> </ul> </li> <?php } else { ?> <li> <a <?php echo $href; ?> ><?php echo $icon . Sanitize::sanitizeTagContent($menu_item_obj->getText()); ?> </a> </li> <?php } } ?> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <?php $h1_str = ''; //$breadcrumbs_arr = ConfWrapper::getOptionalValue(\OLOG\BT\BTConstants::MODULE_NAME . '.' . \OLOG\BT\BTConstants::BREADCRUMBS_PREFIX_ARR, []); //$breadcrumbs_arr = BTConfig::getBreadcrumbsPrefixArr(); $breadcrumbs_arr = []; if ($action_obj) { /* if ($action_obj instanceof InterfaceBreadcrumbs) { $breadcrumbs_arr = array_merge($breadcrumbs_arr, $action_obj->currentBreadcrumbsArr()); } */ if ($action_obj instanceof \OLOG\Layouts\InterfaceTopActionObj) { $top_action_obj = $action_obj->topActionObj(); $extra_breadcrumbs_arr = []; while ($top_action_obj) { $top_action_title = '#NO_TITLE#'; if ($top_action_obj instanceof \OLOG\Layouts\InterfacePageTitle) { $top_action_title = $top_action_obj->pageTitle(); } $top_action_url = '#NO_URL#'; if ($top_action_obj instanceof InterfaceAction) { $top_action_url = $top_action_obj->url(); } array_unshift($extra_breadcrumbs_arr, HTML::a($top_action_url, $top_action_title)); $top_action_obj = null; if ($top_action_obj instanceof \OLOG\Layouts\InterfaceTopActionObj) { $top_action_obj = $top_action_obj->topActionObj(); } } $breadcrumbs_arr = array_merge($breadcrumbs_arr, $extra_breadcrumbs_arr); } if ($action_obj instanceof \OLOG\Layouts\InterfacePageTitle) { $h1_str = $action_obj->pageTitle(); } } if (!empty($breadcrumbs_arr)) { echo BT::breadcrumbs($breadcrumbs_arr); } ?> <div class="page-header"> <h1> <?php echo $h1_str; ?> <?php if ($page_toolbar_html != '') { echo '<span>' . $page_toolbar_html . '</span>'; } ?> </h1> </div> <?php echo $content_html; ?> </div> </body> </html> <?php }
/** * table_id - это идентификатор таблицы на странице, к которому привязываются все данные: имена полей формы и т.п. * @param $model_class_name * @param $create_form_html * @param $column_obj_arr * @param array $filters_arr * @param string $order_by * @return string */ public static function html($model_class_name, $create_form_html, $column_obj_arr, $filters_arr = [], $order_by = '', $table_id = '', $filters_position = self::FILTERS_POSITION_NONE) { // TODO: придумать способ автогенерации table_id, который был бы уникальным, но при этом один и тот же когда одну таблицу запрашиваешь несколько раз self::executeOperations(); // // вывод таблицы // $table_container_element_id = uniqid('tableContainer_'); if ($table_id) { $table_container_element_id = $table_id; } // оборачиваем в отдельный div для выдачи только таблицы аяксом - иначе корневой элемент документа не будет доступен в jquery селекторах $html = HTML::div($table_container_element_id, '', function () use($model_class_name, $create_form_html, $column_obj_arr, $filters_arr, $order_by, $table_id, $filters_position) { echo '<div class="row">'; if ($filters_position == self::FILTERS_POSITION_LEFT) { echo '<div class="col-sm-4">'; echo self::filtersHtml($table_id, $filters_arr); echo '</div>'; } $col_sm_class = '12'; if ($filters_position == self::FILTERS_POSITION_LEFT || $filters_position == self::FILTERS_POSITION_RIGHT) { $col_sm_class = '8'; } echo '<div class="col-sm-' . $col_sm_class . '">'; echo self::toolbarHtml($table_id, $create_form_html, $filters_arr); if ($filters_position == self::FILTERS_POSITION_TOP) { echo self::filtersHtml($table_id, $filters_arr); } if ($filters_position == self::FILTERS_POSITION_INLINE) { echo self::filtersHtmlInline($table_id, $filters_arr); } echo '<table class="table table-hover">'; /** @var InterfaceCRUDTableColumn $column_obj */ echo '<thead><tr>'; foreach ($column_obj_arr as $column_obj) { Assert::assert($column_obj instanceof InterfaceCRUDTableColumn); echo '<th>' . Sanitize::sanitizeTagContent($column_obj->getTitle()) . '</th>'; } echo '</tr></thead>'; echo '<tbody>'; $objs_ids_arr = CRUDInternalTableObjectsSelector::getObjIdsArrForClassName($table_id, $model_class_name, $filters_arr, $order_by); foreach ($objs_ids_arr as $obj_id) { $obj_obj = CRUDObjectLoader::createAndLoadObject($model_class_name, $obj_id); /** @var InterfaceCRUDTableColumn $column_obj */ echo '<tr>'; foreach ($column_obj_arr as $column_obj) { Assert::assert($column_obj instanceof InterfaceCRUDTableColumn); /** @var InterfaceCRUDTableWidget $widget_obj */ $widget_obj = $column_obj->getWidgetObj(); Assert::assert($widget_obj); Assert::assert($widget_obj instanceof InterfaceCRUDTableWidget); $col_width_attr = ''; if ($widget_obj instanceof CRUDTableWidgetDelete) { $col_width_attr = ' width="1px" '; } if ($widget_obj instanceof CRUDTableWidgetWeight) { $col_width_attr = ' width="1px" '; } echo '<td ' . $col_width_attr . ' style="word-break: break-all;">'; echo $widget_obj->html($obj_obj); echo '</td>'; } echo '</tr>'; } echo '</tbody>'; echo '</table>'; echo Pager::renderPager($table_id, count($objs_ids_arr)); echo '</div>'; if ($filters_position == self::FILTERS_POSITION_RIGHT) { echo '<div class="col-sm-4">'; echo self::filtersHtml($table_id, $filters_arr); echo '</div>'; } echo '</div>'; }); // Загрузка скриптов $html .= CRUDTableScript::getHtml($table_container_element_id, Url::getCurrentUrlNoGetForm()); return $html; }
public static function loadSqlArrForDB($db_name) { $filename = self::getSqlFileNameForDB($db_name); if (!file_exists($filename)) { echo "Не найден файл SQL запросов для БД " . $db_name . ": " . $filename . "\n"; echo "Введите 1 чтобы создать файл SQL запросов, ENTER для выхода:\n"; $command_str = trim(fgets(STDIN)); if ($command_str == '1') { // TODO: check errors file_put_contents($filename, var_export([], true)); } else { exit; } } // TODO: must open file from current project root $sql_file_str = file_get_contents($filename); // TODO: better errors check? \OLOG\Assert::assert($sql_file_str, 'SQL queries file doesnt exist or empty.'); $sql_arr = array(); eval('$sql_arr = ' . $sql_file_str . ';'); ksort($sql_arr); return $sql_arr; }
public static function get() { \OLOG\Assert::assert(self::$config_arr); return self::$config_arr; }
/** * ид объекта может быть пустым - тогда при сохранении формы создаст новый объект * @param $obj * @param $element_obj_arr * @param string $url_to_redirect_after_save * @param array $redirect_get_params_arr * @return string html-код формы редактирования * @throws \Exception */ public static function html($obj, $element_obj_arr, $url_to_redirect_after_save = '', $redirect_get_params_arr = [], $form_id = '', $operation_code = self::OPERATION_SAVE_EDITOR_FORM, $hide_submit_button = false) { self::executeOperations($url_to_redirect_after_save, $redirect_get_params_arr); $form_element_id = 'formElem_' . uniqid(); if ($form_id) { $form_element_id = $form_id; } $html = ''; $html .= '<form id="' . $form_element_id . '" class="form-horizontal" role="form" method="post" action="' . Sanitize::sanitizeUrl(\OLOG\Url::getCurrentUrl()) . '">'; $html .= Operations::operationCodeHiddenField($operation_code); $html .= '<input type="hidden" name="' . self::FIELD_CLASS_NAME . '" value="' . Sanitize::sanitizeAttrValue(get_class($obj)) . '">'; $html .= '<input type="hidden" name="' . self::FIELD_OBJECT_ID . '" value="' . Sanitize::sanitizeAttrValue(CRUDFieldsAccess::getObjId($obj)) . '">'; /** @var InterfaceCRUDFormRow $element_obj */ foreach ($element_obj_arr as $element_obj) { Assert::assert($element_obj instanceof InterfaceCRUDFormRow); $html .= $element_obj->html($obj); } $html .= '<div class="row">'; $html .= '<div class="col-sm-8 col-sm-offset-4">'; if (!$hide_submit_button) { $html .= '<button style="width: 100%" type="submit" class="btn btn-primary">Сохранить</button>'; } $html .= '</div>'; $html .= '</div>'; $html .= '</form>'; // Загрузка скриптов $html .= CRUDFormScript::getHtml($form_element_id); return $html; }
public function addForeignKey() { Assert::assert($this->field_name); Assert::assert($this->model_file_path); $model_db_id = $this->getDbIdFromClassFile(); $model_table_name = $this->getTableNameFromClassFile(); Assert::assert($model_table_name); Assert::assert($model_db_id); // TODO: select model instead of table name? echo "Enter target db table name:\n"; $target_table_name = trim(fgets(STDIN)); // TODO: check table name format // TODO: select from target model fields? echo "Enter target db table field name:\n"; $target_field_name = trim(fgets(STDIN)); // TODO: check field name format $on_delete_action = ''; echo "Choose foreign key action on delete:\n"; echo "\tc: cascade (delete this model when deleting referenced model)\n"; echo "\tENTER: default action (restrict deleting referenced model)\n"; $delete_action_code = trim(fgets(STDIN)); if ($delete_action_code == 'c') { $on_delete_action = ' on delete cascade '; } $sql = 'alter table ' . $model_table_name . ' add constraint FK_' . $this->field_name . '_' . rand(0, 999999) . ' foreign key (' . $this->field_name . ') references ' . $target_table_name . ' (' . $target_field_name . ') ' . $on_delete_action . '/* rand' . rand(0, 999999) . ' */;'; CLIExecuteSql::addSqlToRegistry($model_db_id, $sql); echo "\nSQL registry updated\n"; }
/** * @param $db_id * @return DBSettings */ public static function getDBSettingsObj($db_id) { Assert::assert(array_key_exists($db_id, self::$dbsettings_obj_arr)); return self::$dbsettings_obj_arr[$db_id]; }