diff --git a/custom/HungNG_CI_Base_Custom_Model_Credentials_model.php b/custom/HungNG_CI_Base_Custom_Model_Credentials_model.php index db477d5..f7de954 100644 --- a/custom/HungNG_CI_Base_Custom_Model_Credentials_model.php +++ b/custom/HungNG_CI_Base_Custom_Model_Credentials_model.php @@ -50,6 +50,10 @@ public function __destruct() { if ($this->db->conn_id) { $this->db->close(); + log_message( + 'info', + 'HungNG_CI_Base_Custom_Model_Credentials_model - Database disconnected successfully!' + ); } } diff --git a/hungng/HungNG_Custom_Based_model.php b/hungng/HungNG_Custom_Based_model.php index a35e982..f734a38 100644 --- a/hungng/HungNG_Custom_Based_model.php +++ b/hungng/HungNG_Custom_Based_model.php @@ -160,6 +160,7 @@ public function __destruct() { if ($this->db->conn_id) { $this->db->close(); + log_message('info', 'HungNG_Custom_Based_model - Database disconnected successfully!'); } } diff --git a/hungng/HungNG_Model.php b/hungng/HungNG_Model.php index 2a4f915..c8a1c88 100644 --- a/hungng/HungNG_Model.php +++ b/hungng/HungNG_Model.php @@ -1,4 +1,5 @@ _set_connection(); $this->_set_timestamps(); $this->_fetch_table(); - $this->pagination_delimiters = (isset($this->pagination_delimiters)) ? $this->pagination_delimiters : array('', - ''); - $this->pagination_arrows = (isset($this->pagination_arrows)) ? $this->pagination_arrows : array('<', - '>'); + $this->pagination_delimiters = (isset($this->pagination_delimiters)) ? $this->pagination_delimiters : array( + '', + '' + ); + $this->pagination_arrows = (isset($this->pagination_arrows)) ? $this->pagination_arrows : array( + '<', + '>' + ); /* These below are implementation examples for before_create and before_update triggers. Their respective functions - add_creator() and add_updater() - can be found at the end of the model. They add user id on create and update. If you comment this out don't forget to do the same for the methods() @@ -201,6 +206,14 @@ public function __construct() */ } + public function __destruct() + { + if ($this->db->conn_id) { + $this->db->close(); + log_message('info', 'HungNG_Model - Database disconnected successfully!'); + } + } + public function _get_table_fields() { if (empty($this->table_fields)) { @@ -242,7 +255,7 @@ public function _prep_before_write($data) // We make sure we have the fields that can be filled $can_fill = $this->_can_be_filled; // Let's make sure we receive an array... - $data_as_array = (is_object($data)) ? (array) $data : $data; + $data_as_array = (is_object($data)) ? (array)$data : $data; $new_data = array(); $multi = $this->is_multidimensional($data); if ($multi === false) { @@ -312,9 +325,9 @@ public function _prep_after_read($data, $multi = true) * public function from_form($rules = NULL,$additional_values = array(), $row_fields_to_update = array()) * Gets data from form, after validating it and waits for an insert() or update() method in the query chain * - * @param null $rules Gets the validation rules. If nothing is passed (NULL), will look for the + * @param null $rules Gets the validation rules. If nothing is passed (NULL), will look for the * validation rules inside the model $rules public property - * @param array $additional_values Accepts additional fields to be filled, fields that are not to be found + * @param array $additional_values Accepts additional fields to be filled, fields that are not to be found * inside * the form. The values are inserted as an array with "field_name" => * "field_value" @@ -453,9 +466,9 @@ public function is_multidimensional($array) * Updates data into table. Can receive an array or a multidimensional array depending on what kind of update we're * talking about. * - * @param array $data + * @param array $data * @param array|int $column_name_where - * @param bool $escape should the values be escaped or not - defaults to true + * @param bool $escape should the values be escaped or not - defaults to true * * @return str/array Returns id/ids of inserted rows */ @@ -550,19 +563,25 @@ public function update($data = null, $column_name_where = null, $escape = true) * public function where($field_or_array = NULL, $operator_or_value = NULL, $value = NULL, $with_or = FALSE, * $with_not = FALSE, $custom_string = FALSE) Sets a where method for the $this object * - * @param null $field_or_array - can receive a field name or an array with more wheres... + * @param null $field_or_array - can receive a field name or an array with more wheres... * @param null $operator_or_value - can receive a database operator or, if it has a field, the value to equal with - * @param null $value - a value if it received a field name and an operator - * @param bool $with_or - if set to true will create a or_where query type pr a or_like query type, + * @param null $value - a value if it received a field name and an operator + * @param bool $with_or - if set to true will create a or_where query type pr a or_like query type, * depending on the operator - * @param bool $with_not - if set to true will also add "NOT" in the where - * @param bool $custom_string - if set to true, will simply assume that $field_or_array is actually a string + * @param bool $with_not - if set to true will also add "NOT" in the where + * @param bool $custom_string - if set to true, will simply assume that $field_or_array is actually a string * and pass it to the where query * * @return $this */ - public function where($field_or_array = null, $operator_or_value = null, $value = null, $with_or = false, $with_not = false, $custom_string = false) - { + public function where( + $field_or_array = null, + $operator_or_value = null, + $value = null, + $with_or = false, + $with_not = false, + $custom_string = false + ) { if ($this->soft_deletes === true) { $backtrace = debug_backtrace(); #fix for lower PHP 5.4 version if ($backtrace[1]['function'] != 'force_delete') { @@ -600,9 +619,13 @@ public function where($field_or_array = null, $operator_or_value = null, $value $this->_database->{$where_or}(array($this->table . '.' . $this->primary_key => $field_or_array)); } elseif (is_array($field_or_array) && !isset($operator_or_value)) { $this->_database->where($field_or_array); - } elseif (!isset($value) && isset($field_or_array) && isset($operator_or_value) && !is_array($operator_or_value)) { + } elseif (!isset($value) && isset($field_or_array) && isset($operator_or_value) && !is_array( + $operator_or_value + )) { $this->_database->{$where_or}(array($this->table . '.' . $field_or_array => $operator_or_value)); - } elseif (!isset($value) && isset($field_or_array) && isset($operator_or_value) && is_array($operator_or_value) && !is_array($field_or_array)) { + } elseif (!isset($value) && isset($field_or_array) && isset($operator_or_value) && is_array( + $operator_or_value + ) && !is_array($field_or_array)) { //echo $field_or_array; //exit; $this->_database->{$where_or . $not . '_in'}($this->table . '.' . $field_or_array, $operator_or_value); @@ -791,14 +814,22 @@ public function trashed($where = null) public function _get_joined($requested) { - $this->_database->join($this->_relationships[$requested['request']]['foreign_table'], $this->table . '.' . $this->_relationships[$requested['request']]['local_key'] . ' = ' . $this->_relationships[$requested['request']]['foreign_table'] . '.' . $this->_relationships[$requested['request']]['foreign_key']); + $this->_database->join( + $this->_relationships[$requested['request']]['foreign_table'], + $this->table . '.' . $this->_relationships[$requested['request']]['local_key'] . ' = ' . $this->_relationships[$requested['request']]['foreign_table'] . '.' . $this->_relationships[$requested['request']]['foreign_key'] + ); $the_select = ''; if (!empty($requested['parameters'])) { if (array_key_exists('fields', $requested['parameters'])) { $fields = explode(',', $requested['parameters']['fields']); $sub_select = array(); foreach ($fields as $field) { - $sub_select[] = ((strpos($field, '.') === false) ? '`' . $this->_relationships[$requested['request']]['foreign_table'] . '`.`' . trim($field) . '`' : trim($field)) . ' AS ' . $requested['request'] . '_' . trim($field); + $sub_select[] = ((strpos( + $field, + '.' + ) === false) ? '`' . $this->_relationships[$requested['request']]['foreign_table'] . '`.`' . trim( + $field + ) . '`' : trim($field)) . ' AS ' . $requested['request'] . '_' . trim($field); } $the_select = implode(',', $sub_select); } else { @@ -822,7 +853,9 @@ public function get($where = null) $data = $this->_get_from_cache(); if (isset($data) && $data !== false) { $this->_database->reset_query(); - if (isset($this->_cache)) unset($this->_cache); + if (isset($this->_cache)) { + unset($this->_cache); + } return $data; } else { @@ -874,7 +907,9 @@ public function get_all($where = null) $data = $this->_get_from_cache(); if (isset($data) && $data !== false) { $this->_database->reset_query(); - if (isset($this->_cache)) unset($this->_cache); + if (isset($this->_cache)) { + unset($this->_cache); + } return $data; } else { @@ -939,7 +974,7 @@ public function count_rows($where = null) * the constructor * * @param string $request - * @param array $arguments + * @param array $arguments * * @return $this */ @@ -962,7 +997,9 @@ public function with($request, $arguments = array()) if (sizeof($elements) == 2) { $parameters[$elements[0]] = $elements[1]; } else { - show_error('MY_Model: Parameters for with_*() method must be of the form: "...->with_*(\'where:...|fields:...\')"'); + show_error( + 'MY_Model: Parameters for with_*() method must be of the form: "...->with_*(\'where:...|fields:...\')"' + ); } } } @@ -1023,11 +1060,15 @@ protected function join_temporary_results($data) foreach ($elements as $element) { $order = explode(' ', $element); if (sizeof($order) == 2) { - $order_inside_array[] = array(trim($order[0]), - trim($order[1])); + $order_inside_array[] = array( + trim($order[0]), + trim($order[1]) + ); } else { - $order_inside_array[] = array(trim($order[0]), - 'desc'); + $order_inside_array[] = array( + trim($order[0]), + 'desc' + ); } } } @@ -1055,19 +1096,37 @@ protected function join_temporary_results($data) } else { $fields = explode(',', $request['parameters']['fields']); foreach ($fields as $field) { - $select[] = (strpos($field, '.') === false) ? '`' . $foreign_table . '`.`' . trim($field) . '`' : trim($field); + $select[] = (strpos($field, '.') === false) ? '`' . $foreign_table . '`.`' . trim( + $field + ) . '`' : trim($field); } $the_select = implode(',', $select); $sub_results = (isset($the_select)) ? $sub_results->fields($the_select) : $sub_results; } } - if (array_key_exists('fields', $request['parameters']) && ($request['parameters']['fields'] == '*count*')) { + if (array_key_exists( + 'fields', + $request['parameters'] + ) && ($request['parameters']['fields'] == '*count*')) { $sub_results->group_by('`' . $foreign_table . '`.`' . $foreign_key . '`'); } - if (array_key_exists('where', $request['parameters']) || array_key_exists('non_exclusive_where', $request['parameters'])) { - $the_where = array_key_exists('where', $request['parameters']) ? 'where' : 'non_exclusive_where'; + if (array_key_exists('where', $request['parameters']) || array_key_exists( + 'non_exclusive_where', + $request['parameters'] + )) { + $the_where = array_key_exists( + 'where', + $request['parameters'] + ) ? 'where' : 'non_exclusive_where'; } - $sub_results = isset($the_where) ? $sub_results->where($request['parameters'][$the_where], null, null, false, false, true) : $sub_results; + $sub_results = isset($the_where) ? $sub_results->where( + $request['parameters'][$the_where], + null, + null, + false, + false, + true + ) : $sub_results; if (isset($order_inside_array)) { foreach ($order_inside_array as $order_by_inside) { $sub_results = $sub_results->order_by($order_by_inside[0], $order_by_inside[1]); @@ -1076,7 +1135,11 @@ protected function join_temporary_results($data) //Add nested relation if (array_key_exists('with', $request['parameters'])) { // Do we have many nested relation - if (is_array($request['parameters']['with']) && isset($request['parameters']['with'][0]) && is_array($request['parameters']['with'][0])) { + if (is_array( + $request['parameters']['with'] + ) && isset($request['parameters']['with'][0]) && is_array( + $request['parameters']['with'][0] + )) { foreach ($request['parameters']['with'] as $with) { $with_relation = array_shift($with); $sub_results->with($with_relation, array($with)); @@ -1090,26 +1153,45 @@ protected function join_temporary_results($data) } $sub_results = $sub_results->where($foreign_key, $local_key_values)->get_all(); } else { - $this->_database->join($pivot_table, $foreign_table . '.' . $foreign_key . ' = ' . $pivot_table . '.' . $pivot_foreign_key, 'left'); - $this->_database->join($this->table, $pivot_table . '.' . $pivot_local_key . ' = ' . $this->table . '.' . $local_key, 'left'); + $this->_database->join( + $pivot_table, + $foreign_table . '.' . $foreign_key . ' = ' . $pivot_table . '.' . $pivot_foreign_key, + 'left' + ); + $this->_database->join( + $this->table, + $pivot_table . '.' . $pivot_local_key . ' = ' . $this->table . '.' . $local_key, + 'left' + ); $this->_database->select($foreign_table . '.' . $foreign_key); $this->_database->select($pivot_table . '.' . $pivot_local_key); if (!empty($request['parameters'])) { if (array_key_exists('fields', $request['parameters'])) { if ($request['parameters']['fields'] == '*count*') { - $this->_database->select('COUNT(`' . $foreign_table . '`.`' . $foreign_key . '`) as counted_rows, `' . $foreign_table . '`.`' . $foreign_key . '`', false); + $this->_database->select( + 'COUNT(`' . $foreign_table . '`.`' . $foreign_key . '`) as counted_rows, `' . $foreign_table . '`.`' . $foreign_key . '`', + false + ); } else { $fields = explode(',', $request['parameters']['fields']); $select = array(); foreach ($fields as $field) { - $select[] = (strpos($field, '.') === false) ? '`' . $foreign_table . '`.`' . trim($field) . '`' : trim($field); + $select[] = (strpos($field, '.') === false) ? '`' . $foreign_table . '`.`' . trim( + $field + ) . '`' : trim($field); } $the_select = implode(',', $select); $this->_database->select($the_select); } } - if (array_key_exists('where', $request['parameters']) || array_key_exists('non_exclusive_where', $request['parameters'])) { - $the_where = array_key_exists('where', $request['parameters']) ? 'where' : 'non_exclusive_where'; + if (array_key_exists('where', $request['parameters']) || array_key_exists( + 'non_exclusive_where', + $request['parameters'] + )) { + $the_where = array_key_exists( + 'where', + $request['parameters'] + ) ? 'where' : 'non_exclusive_where'; $this->_database->where($request['parameters'][$the_where], null, null, false, false, true); } } @@ -1117,7 +1199,10 @@ protected function join_temporary_results($data) if (!empty($order_inside_array)) { $order_inside_str = ''; foreach ($order_inside_array as $order_by_inside) { - $order_inside_str .= (strpos($order_by_inside[0], ',') === false) ? '`' . $foreign_table . '`.`' . $order_by_inside[0] . ' ' . $order_by_inside[1] : $order_by_inside[0] . ' ' . $order_by_inside[1]; + $order_inside_str .= (strpos( + $order_by_inside[0], + ',' + ) === false) ? '`' . $foreign_table . '`.`' . $order_by_inside[0] . ' ' . $order_by_inside[1] : $order_by_inside[0] . ' ' . $order_by_inside[1]; $order_inside_str .= ','; } $order_inside_str = rtrim($order_inside_str, ","); @@ -1129,12 +1214,15 @@ protected function join_temporary_results($data) if (isset($sub_results) && !empty($sub_results)) { $subs = array(); foreach ($sub_results as $result) { - $result_array = (array) $result; + $result_array = (array)$result; $the_foreign_key = $result_array[$foreign_key]; if (isset($pivot_table)) { $the_local_key = $result_array[$pivot_local_key]; if (isset($get_relate) and $get_relate === true) { - $subs[$the_local_key][$the_foreign_key] = $this->{$relation['foreign_model']}->where($foreign_key, $result[$foreign_key])->get(); + $subs[$the_local_key][$the_foreign_key] = $this->{$relation['foreign_model']}->where( + $foreign_key, + $result[$foreign_key] + )->get(); } else { $subs[$the_local_key][$the_foreign_key] = $result; } @@ -1162,11 +1250,15 @@ protected function join_temporary_results($data) if (array_key_exists('order_by', $request['parameters'])) { $elements = explode(',', $request['parameters']['order_by']); if (sizeof($elements) == 2) { - $order_by[$relation_key] = array(trim($elements[0]), - trim($elements[1])); + $order_by[$relation_key] = array( + trim($elements[0]), + trim($elements[1]) + ); } else { - $order_by[$relation_key] = array(trim($elements[0]), - 'desc'); + $order_by[$relation_key] = array( + trim($elements[0]), + 'desc' + ); } } unset($this->_requested[$requested_key]); @@ -1193,7 +1285,11 @@ protected function join_temporary_results($data) private function _has_one($request) { $relation = $this->_relationships[$request]; - $this->_database->join($relation['foreign_table'], $relation['foreign_table'] . '.' . $relation['foreign_key'] . ' = ' . $this->table . '.' . $relation['local_key'], 'left'); + $this->_database->join( + $relation['foreign_table'], + $relation['foreign_table'] . '.' . $relation['foreign_key'] . ' = ' . $this->table . '.' . $relation['local_key'], + 'left' + ); return true; } @@ -1206,9 +1302,11 @@ private function _has_one($request) private function _set_relationships() { if (empty($this->_relationships)) { - $options = array('has_one', - 'has_many', - 'has_many_pivot'); + $options = array( + 'has_one', + 'has_many', + 'has_many_pivot' + ); foreach ($options as $option) { if (isset($this->{$option}) && !empty($this->{$option})) { foreach ($this->{$option} as $key => $relation) { @@ -1242,9 +1340,18 @@ private function _set_relationships() $local_key = $relation['local_key']; if ($option == 'has_many_pivot') { $pivot_table = $relation['pivot_table']; - $pivot_local_key = (array_key_exists('pivot_local_key', $relation)) ? $relation['pivot_local_key'] : $this->table . '_' . $this->primary_key; - $pivot_foreign_key = (array_key_exists('pivot_foreign_key', $relation)) ? $relation['pivot_foreign_key'] : $foreign_table . '_' . $foreign_key; - $get_relate = (array_key_exists('get_relate', $relation) && ($relation['get_relate'] === true)) ? true : false; + $pivot_local_key = (array_key_exists( + 'pivot_local_key', + $relation + )) ? $relation['pivot_local_key'] : $this->table . '_' . $this->primary_key; + $pivot_foreign_key = (array_key_exists( + 'pivot_foreign_key', + $relation + )) ? $relation['pivot_foreign_key'] : $foreign_table . '_' . $foreign_key; + $get_relate = (array_key_exists( + 'get_relate', + $relation + ) && ($relation['get_relate'] === true)) ? true : false; } if ($option == 'has_one' && isset($relation['join']) && $relation['join'] === true) { $single_query = true; @@ -1266,18 +1373,22 @@ private function _set_relationships() } } if ($option == 'has_many_pivot' && !isset($pivot_table)) { - $tables = array($this->table, - $foreign_table); + $tables = array( + $this->table, + $foreign_table + ); sort($tables); $pivot_table = $tables[0] . '_' . $tables[1]; } - $this->_relationships[$key] = array('relation' => $option, - 'relation_key' => $key, - 'foreign_model' => bear_str_to_lower($foreign_model), - 'foreign_model_name' => bear_str_to_lower($foreign_model_name), - 'foreign_table' => $foreign_table, - 'foreign_key' => $foreign_key, - 'local_key' => $local_key); + $this->_relationships[$key] = array( + 'relation' => $option, + 'relation_key' => $key, + 'foreign_model' => bear_str_to_lower($foreign_model), + 'foreign_model_name' => bear_str_to_lower($foreign_model_name), + 'foreign_table' => $foreign_table, + 'foreign_key' => $foreign_key, + 'local_key' => $local_key + ); if ($option == 'has_many_pivot') { $this->_relationships[$key]['pivot_table'] = $pivot_table; $this->_relationships[$key]['pivot_local_key'] = $pivot_local_key; @@ -1342,9 +1453,13 @@ public function trigger($event, $data = array(), $last = true) $method = $matches[1]; $this->callback_parameters = explode(',', $matches[3]); } - $data = call_user_func_array(array($this, - $method), array($data, - $last)); + $data = call_user_func_array(array( + $this, + $method + ), array( + $data, + $last + )); } } @@ -1399,7 +1514,11 @@ private function _where_trashed() { switch ($this->_trashed) { case 'only': - $this->_database->where($this->table . '.' . $this->_deleted_at_field . ' IS NOT NULL', null, false); + $this->_database->where( + $this->table . '.' . $this->_deleted_at_field . ' IS NOT NULL', + null, + false + ); break; case 'without': $this->_database->where($this->table . '.' . $this->_deleted_at_field . ' IS NULL', null, false); @@ -1491,13 +1610,17 @@ public function as_object() public function as_dropdown($field = null) { if (!isset($field)) { - show_error('MY_Model: You must set a field to be set as value for the key: ...->as_dropdown(\'field\')->...'); + show_error( + 'MY_Model: You must set a field to be set as value for the key: ...->as_dropdown(\'field\')->...' + ); exit; } $this->return_as_dropdown = 'dropdown'; $this->_dropdown_field = $field; - $this->_select = array($this->primary_key, - $field); + $this->_select = array( + $this->primary_key, + $field + ); return $this; } @@ -1534,8 +1657,10 @@ public function set_cache($string, $seconds = 86400) { $prefix = (bear_str_length($this->cache_prefix) > 0) ? $this->cache_prefix . '_' : ''; $prefix .= $this->table . '_'; - $this->_cache = array('cache_name' => $prefix . $string, - 'seconds' => $seconds); + $this->_cache = array( + 'cache_name' => $prefix . $string, + 'seconds' => $seconds + ); return $this; } @@ -1581,9 +1706,15 @@ public function delete_cache($string = null) private function _set_timestamps() { if ($this->timestamps !== false) { - $this->_created_at_field = (is_array($this->timestamps) && isset($this->timestamps[0])) ? $this->timestamps[0] : 'created_at'; - $this->_updated_at_field = (is_array($this->timestamps) && isset($this->timestamps[1])) ? $this->timestamps[1] : 'updated_at'; - $this->_deleted_at_field = (is_array($this->timestamps) && isset($this->timestamps[2])) ? $this->timestamps[2] : 'deleted_at'; + $this->_created_at_field = (is_array( + $this->timestamps + ) && isset($this->timestamps[0])) ? $this->timestamps[0] : 'created_at'; + $this->_updated_at_field = (is_array( + $this->timestamps + ) && isset($this->timestamps[1])) ? $this->timestamps[1] : 'updated_at'; + $this->_deleted_at_field = (is_array( + $this->timestamps + ) && isset($this->timestamps[2])) ? $this->timestamps[2] : 'deleted_at'; } return true; @@ -1646,14 +1777,20 @@ public function paginate($rows_per_page, $total_rows = null, $page_number = 1) } else { $uri_array[$segments] = $previous_page; $uri_string = implode('/', $uri_array); - $this->previous_page = $this->pagination_delimiters[0] . anchor($uri_string, $this->pagination_arrows[0]) . $this->pagination_delimiters[1]; + $this->previous_page = $this->pagination_delimiters[0] . anchor( + $uri_string, + $this->pagination_arrows[0] + ) . $this->pagination_delimiters[1]; } $uri_array[$segments] = $next_page; $uri_string = implode('/', $uri_array); if (isset($total_rows) && (ceil($total_rows / $rows_per_page) == $page_number)) { $this->next_page = $this->pagination_delimiters[0] . $this->pagination_arrows[1] . $this->pagination_delimiters[1]; } else { - $this->next_page = $this->pagination_delimiters[0] . anchor($uri_string, $this->pagination_arrows[1]) . $this->pagination_delimiters[1]; + $this->next_page = $this->pagination_delimiters[0] . anchor( + $uri_string, + $this->pagination_arrows[1] + ) . $this->pagination_delimiters[1]; } $rows_per_page = (is_numeric($rows_per_page)) ? $rows_per_page : 10; if (isset($total_rows)) { @@ -1755,14 +1892,18 @@ public function __call($method, $arguments) return $this; } if (method_exists($this->_database, $method)) { - call_user_func_array(array($this->_database, - $method), $arguments); + call_user_func_array(array( + $this->_database, + $method + ), $arguments); return $this; } $parent_class = get_parent_class($this); if ($parent_class !== false && !method_exists($parent_class, $method) && !method_exists($this, $method)) { - $msg = 'The method "' . $method . '" does not exist in ' . get_class($this) . ' or MY_Model or CI_Model.'; + $msg = 'The method "' . $method . '" does not exist in ' . get_class( + $this + ) . ' or MY_Model or CI_Model.'; show_error($msg, EXIT_UNKNOWN_METHOD, 'Method Not Found'); } } @@ -1773,7 +1914,9 @@ private function _build_sorter($data, $field, $order_by, $sort_by = 'DESC') $array_a = isset($a[$field]) ? $this->object_to_array($a[$field]) : null; $array_b = isset($b[$field]) ? $this->object_to_array($b[$field]) : null; - return strtoupper($sort_by) == "DESC" ? ((isset($array_a[$order_by]) && isset($array_b[$order_by])) ? ($array_a[$order_by] < $array_b[$order_by]) : (!isset($array_a) ? 1 : -1)) : ((isset($array_a[$order_by]) && isset($array_b[$order_by])) ? ($array_a[$order_by] > $array_b[$order_by]) : (!isset($array_b) ? 1 : -1)); + return strtoupper( + $sort_by + ) == "DESC" ? ((isset($array_a[$order_by]) && isset($array_b[$order_by])) ? ($array_a[$order_by] < $array_b[$order_by]) : (!isset($array_a) ? 1 : -1)) : ((isset($array_a[$order_by]) && isset($array_b[$order_by])) ? ($array_a[$order_by] > $array_b[$order_by]) : (!isset($array_b) ? 1 : -1)); }); return $data; @@ -1788,8 +1931,10 @@ public function object_to_array($object) $object = get_object_vars($object); } - return array_map(array($this, - 'object_to_array'), $object); + return array_map(array( + $this, + 'object_to_array' + ), $object); } /** @@ -1801,7 +1946,7 @@ public function object_to_array($object) */ protected function is_assoc(array $array) { - return (bool) count(array_filter(array_keys($array), 'is_string')); + return (bool)count(array_filter(array_keys($array), 'is_string')); } /** diff --git a/hungng/HungNG_ORM_Model.php b/hungng/HungNG_ORM_Model.php index d26d832..e390a38 100644 --- a/hungng/HungNG_ORM_Model.php +++ b/hungng/HungNG_ORM_Model.php @@ -1,4 +1,5 @@ db->conn_id) { + $this->db->close(); + log_message('info', 'HungNG_ORM_Mdel - Database disconnected successfully!'); + } + } + /** * Get Master Database Connection * @@ -356,9 +365,8 @@ public function validate($attributes = array(), $returnData = false) // The ORM update will only collect rules with corresponding modified attributes. if ($this->_selfCondition) { - $newRules = array(); - foreach ((array) $rules as $key => $rule) { + foreach ((array)$rules as $key => $rule) { if (isset($this->_writeProperties[$rule['field']])) { // Add into new rules for updating $newRules[] = $rule; @@ -369,12 +377,14 @@ public function validate($attributes = array(), $returnData = false) } // Check if has rules - if (empty($rules)) + if (empty($rules)) { return ($returnData) ? $data : true; + } // CodeIgniter form_validation doesn't work with empty array data - if (empty($data)) + if (empty($data)) { return false; + } // Load CodeIgniter form_validation library for yidas/model namespace, which has no effect on common one get_instance()->load->library('form_validation', null, 'yidas_model_form_validation'); @@ -388,13 +398,10 @@ public function validate($attributes = array(), $returnData = false) // Result handle if ($result === false) { - $this->_errors = $validator->error_array(); return false; - } else { - return ($returnData) ? $data : true; } } @@ -435,14 +442,19 @@ public function filter($data) // Filter process with setting check if (!empty($filters) && is_array($filters)) { - foreach ($filters as $key => $filter) { + if (!isset($filter[0])) { + throw new Exception( + "No attributes defined in \$filters from " . get_called_class() . " (" . __CLASS__ . ")", + 500 + ); + } - if (!isset($filter[0])) - throw new Exception("No attributes defined in \$filters from " . get_called_class() . " (" . __CLASS__ . ")", 500); - - if (!isset($filter[1])) - throw new Exception("No function defined in \$filters from " . get_called_class() . " (" . __CLASS__ . ")", 500); + if (!isset($filter[1])) { + throw new Exception( + "No function defined in \$filters from " . get_called_class() . " (" . __CLASS__ . ")", 500 + ); + } list($attributes, $function) = $filter; @@ -450,9 +462,9 @@ public function filter($data) // Filter each attribute foreach ($attributes as $key => $attribute) { - - if (!isset($data[$attribute])) + if (!isset($data[$attribute])) { continue; + } $data[$attribute] = call_user_func($function, $data[$attribute]); } @@ -566,8 +578,8 @@ public static function findOne($condition = ) } $record = $instance->_findByCondition($condition) - ->limit(1) - ->get()->row_array(); + ->limit(1) + ->get()->row_array(); // Record check if (!$record) { @@ -580,8 +592,8 @@ public static function findOne($condition = ) /** * Returns a list of active record models that match the specified primary key value(s) or a set of column values. * - * @param mixed $condition Refer to _findByCondition() for the explanation - * @param integer|array $limit Limit or [offset, limit] + * @param mixed $condition Refer to _findByCondition() for the explanation + * @param integer|array $limit Limit or [offset, limit] * * @return array Set of ActiveRecord(Model)s * @example @@ -599,7 +611,6 @@ public static function findAll($condition = array(), $limit = null) // Limit / offset if ($limit) { - $offset = null; if (is_array($limit) && isset($limit[1])) { @@ -621,7 +632,7 @@ public static function findAll($condition = array(), $limit = null) $set = array(); // Each ActiveRecord - foreach ((array) $records as $key => $record) { + foreach ((array)$records as $key => $record) { // Check primary key setting if (!isset($record[$instance->primaryKey])) { throw new Exception("Model's primary key not set", 500); @@ -652,7 +663,7 @@ public function reset() /** * Insert a row with Timestamps feature into the associated database table using the attribute values of this record. * - * @param array $attributes + * @param array $attributes * @param boolean $runValidation Whether to perform validation (calling validate()) before manipulate the record. * * @return boolean Result @@ -665,12 +676,15 @@ public function reset() public function insert($attributes, $runValidation = true) { // Validation - if ($runValidation && false === $attributes = $this->validate($attributes, true)) + if ($runValidation && false === $attributes = $this->validate($attributes, true)) { return false; + } $this->_attrEventBeforeInsert($attributes); - if ($this->fillable) $attributes = array_intersect_key($attributes, array_flip($this->fillable)); + if ($this->fillable) { + $attributes = array_intersect_key($attributes, array_flip($this->fillable)); + } return $this->_db->insert($this->table, $attributes); } @@ -678,7 +692,7 @@ public function insert($attributes, $runValidation = true) /** * Insert a batch of rows with Timestamps feature into the associated database table using the attribute values of this record. * - * @param array $data The rows to be batch inserted + * @param array $data The rows to be batch inserted * @param boolean $runValidation Whether to perform validation (calling validate()) before manipulate the record. * * @return int Number of rows inserted or FALSE on failure @@ -691,10 +705,10 @@ public function insert($attributes, $runValidation = true) public function batchInsert($data, $runValidation = true) { foreach ($data as $key => &$attributes) { - // Validation - if ($runValidation && false === $attributes = $this->validate($attributes, true)) + if ($runValidation && false === $attributes = $this->validate($attributes, true)) { return false; + } $this->_attrEventBeforeInsert($attributes); } @@ -717,7 +731,7 @@ public function getLastInsertID($name = null) /** * Replace a row with Timestamps feature into the associated database table using the attribute values of this record. * - * @param array $attributes + * @param array $attributes * @param boolean $runValidation Whether to perform validation (calling validate()) before manipulate the record. * * @return bool Result @@ -731,8 +745,9 @@ public function getLastInsertID($name = null) public function replace($attributes, $runValidation = true) { // Validation - if ($runValidation && false === $attributes = $this->validate($attributes, true)) + if ($runValidation && false === $attributes = $this->validate($attributes, true)) { return false; + } $this->_attrEventBeforeInsert($attributes); @@ -742,8 +757,8 @@ public function replace($attributes, $runValidation = true) /** * Save the changes with Timestamps feature to the selected record(s) into the associated database table. * - * @param array $attributes - * @param mixed $condition Refer to _findByCondition() for the explanation + * @param array $attributes + * @param mixed $condition Refer to _findByCondition() for the explanation * @param boolean $runValidation Whether to perform validation (calling validate()) before manipulate the record. * * @return bool Result @@ -758,15 +773,18 @@ public function replace($attributes, $runValidation = true) public function update($attributes, $condition = null, $runValidation = true) { // Validation - if ($runValidation && false === $attributes = $this->validate($attributes, true)) + if ($runValidation && false === $attributes = $this->validate($attributes, true)) { return false; + } // Model Condition $query = $this->_findByCondition($condition); $attributes = $this->_attrEventBeforeUpdate($attributes); - if ($this->fillable) $attributes = array_intersect_key($attributes, array_flip($this->fillable)); + if ($this->fillable) { + $attributes = array_intersect_key($attributes, array_flip($this->fillable)); + } // Pack query then move it to write DB from read DB $sql = $this->_dbr->set($attributes)->get_compiled_update(); @@ -778,9 +796,9 @@ public function update($attributes, $condition = null, $runValidation = true) /** * Update a batch of update queries into combined query strings. * - * @param array $dataSet [[[Attributes], [Condition]], ] - * @param boolean $withAll withAll() switch helper - * @param integer $maxLenth MySQL max_allowed_packet + * @param array $dataSet [[[Attributes], [Condition]], ] + * @param boolean $withAll withAll() switch helper + * @param integer $maxLenth MySQL max_allowed_packet * @param boolean $runValidation Whether to perform validation (calling validate()) before manipulate the record. * * @return integer Count of successful query pack(s) @@ -792,23 +810,24 @@ public function update($attributes, $condition = null, $runValidation = true) */ public function batchUpdate(array $dataSet, $withAll = false, $maxLength = null, $runValidation = true) { - $maxLength = $maxLength ? : 4 * 1024 * 1024; + $maxLength = $maxLength ?: 4 * 1024 * 1024; $count = 0; $sqlBatch = ''; foreach ($dataSet as $key => &$each) { - // Data format list($attributes, $condition) = $each; // Check attributes - if (!is_array($attributes) || !$attributes) + if (!is_array($attributes) || !$attributes) { continue; + } // Validation - if ($runValidation && false === $attributes = $this->validate($attributes, true)) + if ($runValidation && false === $attributes = $this->validate($attributes, true)) { continue; + } // WithAll helper if ($withAll === true) { @@ -847,9 +866,9 @@ public function batchUpdate(array $dataSet, $withAll = false, $maxLength = null, /** * Delete the selected record(s) with Timestamps feature into the associated database table. * - * @param mixed $condition Refer to _findByCondition() for the explanation + * @param mixed $condition Refer to _findByCondition() for the explanation * @param boolean $forceDelete Force to hard delete - * @param array $attributes Extended attributes for Soft Delete Mode + * @param array $attributes Extended attributes for Soft Delete Mode * * @return bool Result * @@ -881,7 +900,6 @@ public function delete($condition = null, $forceDelete = false, $attributes = ar if (static::SOFT_DELETED && isset($this->softDeletedTrueValue) && !$forceDelete) { - // Mark the records as deleted $attributes[static::SOFT_DELETED] = $this->softDeletedTrueValue; @@ -890,9 +908,7 @@ public function delete($condition = null, $forceDelete = false, $attributes = ar // Pack query then move it to write DB from read DB $sql = $this->_dbr->set($attributes)->get_compiled_update(); $this->_dbr->reset_query(); - } else { - /* Hard Delete */ // Pack query then move it to write DB from read DB $sql = $this->_dbr->get_compiled_delete(); @@ -953,14 +969,11 @@ public function restore($condition = null) /* Soft Delete Mode */ if (static::SOFT_DELETED && isset($this->softDeletedFalseValue)) { - // Mark the records as deleted $attributes[static::SOFT_DELETED] = $this->softDeletedFalseValue; return $query->update($this->table, $attributes); - } else { - return false; } } @@ -982,9 +995,7 @@ public function count($resetQuery = true) * * sharedLock locks only for write, lockForUpdate also prevents them from being selected * - * @example - * $this->Model->find()->where('id', 123) - * $result = $this->Model->lockForUpdate()->row_array(); + * @return object CI_DB_result * @example * // This transaction block will lock selected rows for next same selected * // rows with `FOR UPDATE` lock: @@ -993,7 +1004,9 @@ public function count($resetQuery = true) * $result = $this->Model->lockForUpdate()->row_array(); * $this->Model->getDB()->trans_complete(); * - * @return object CI_DB_result + * @example + * $this->Model->find()->where('id', 123) + * $result = $this->Model->lockForUpdate()->row_array(); */ public function lockForUpdate() { @@ -1007,11 +1020,11 @@ public function lockForUpdate() /** * Share lock the selected rows in the table. * + * @return object CI_DB_result * @example * $this->Model->find()->where('id', 123) * $result = $this->Model->sharedLock()->row_array();' * - * @return object CI_DB_result */ public function sharedLock() { @@ -1100,7 +1113,6 @@ public function save($runValidation = true) // ORM status distinguishing if (!$this->_selfCondition) { - // Event if (!$this->beforeSave(true)) { return false; @@ -1119,18 +1131,19 @@ public function save($runValidation = true) // Reset properties $this->_writeProperties = array(); } - } else { - // Event if (!$this->beforeSave(false)) { return false; } - $result = ($this->_writeProperties) ? $this->update($this->_writeProperties, $this->_selfCondition, $runValidation) : true; + $result = ($this->_writeProperties) ? $this->update( + $this->_writeProperties, + $this->_selfCondition, + $runValidation + ) : true; // Check the primary key is changed if ($result) { - // Primary key condition to ensure single query result if (isset($this->_writeProperties[$this->primaryKey])) { $this->_selfCondition = $this->_writeProperties[$this->primaryKey]; @@ -1164,7 +1177,7 @@ public function beforeSave($insert) /** * This method is called at the end of inserting or updating a active record * - * @param bool $insert whether this method called while inserting a record. + * @param bool $insert whether this method called while inserting a record. * If `false`, it means the method is called while updating a record. * @param array $changedAttributes The old values of attributes that had changed and were saved. * You can use this parameter to take action based on the changes made for example send an email @@ -1223,9 +1236,7 @@ protected function _relationship($modelName, $relationship, $foreignKey = null, * @see https://github.com/yidas/codeigniter-psr4-autoload */ if (strpos($modelName, "\\") !== false) { - $model = new $modelName; - } else { // Original CodeIgniter 3 model loader get_instance()->load->model($modelName); @@ -1247,7 +1258,7 @@ protected function _relationship($modelName, $relationship, $foreignKey = null, $localKey = ($localKey) ? $localKey : $this->primaryKey; $query = $model->find() - ->where($foreignKey, $this->$localKey); + ->where($foreignKey, $this->$localKey); // Inject Model name into query builder for ORM relationships $query->modelName = $modelName; @@ -1287,9 +1298,7 @@ protected function _getRelationshipProperty($method) * @see https://github.com/yidas/codeigniter-psr4-autoload */ if (strpos($modelName, "\\") !== false) { - $model = new $modelName; - } else { // Original CodeIgniter 3 model loader get_instance()->load->model($modelName); @@ -1327,9 +1336,8 @@ public function getTableSchema() // Check ORM Schema cache if (!isset(self::$_ormCaches[$class])) { - $columns = $this->_dbr->query("SHOW COLUMNS FROM `{$this->table}`;") - ->result_array(); + ->result_array(); // Cache self::$_ormCaches[$class] = $columns; @@ -1341,9 +1349,9 @@ public function getTableSchema() /** * Index by Key * - * @param array $array Array data for handling - * @param string $key Array key for index key - * @param bool $obj2Array Object converts to array if is object + * @param array $array Array data for handling + * @param string $key Array key for index key + * @param bool $obj2Array Object converts to array if is object * * @return array Result with indexBy Key * @example @@ -1353,16 +1361,14 @@ public function getTableSchema() public static function indexBy(array &$array, $key = null, $obj2Array = false) { // Use model instance's primary key while no given key - $key = ($key) ? : (new static())->primaryKey; + $key = ($key) ?: (new static())->primaryKey; $tmp = array(); foreach ($array as $row) { // Array & Object types support if (is_object($row) && isset($row->$key)) { - - $tmp[$row->$key] = ($obj2Array) ? (array) $row : $row; + $tmp[$row->$key] = ($obj2Array) ? (array)$row : $row; } elseif (is_array($row) && isset($row[$key])) { - $tmp[$row[$key]] = $row; } } @@ -1375,8 +1381,8 @@ public static function indexBy(array &$array, $key = null, $obj2Array = false) * * The [[$this->config->item('charset')]] will be used for encoding. * - * @param string $content the content to be encoded - * @param bool $doubleEncode whether to encode HTML entities in `$content`. If false, + * @param string $content the content to be encoded + * @param bool $doubleEncode whether to encode HTML entities in `$content`. If false, * HTML entities in `$content` will not be further encoded. * * @return string the encoded content @@ -1388,7 +1394,12 @@ public static function htmlEncode($content, $doubleEncode = true) { $ci = &get_instance(); - return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, $ci->config->item('charset') ? $ci->config->item('charset') : 'UTF-8', $doubleEncode); + return htmlspecialchars( + $content, + ENT_QUOTES | ENT_SUBSTITUTE, + $ci->config->item('charset') ? $ci->config->item('charset') : 'UTF-8', + $doubleEncode + ); } /** @@ -1433,7 +1444,6 @@ protected function _attrEventBeforeInsert(&$attributes) // Trigger UPDATED_AT if ($this->createdWithUpdated) { - $this->_formatDate(static::UPDATED_AT, $attributes); } @@ -1503,18 +1513,13 @@ protected function _findByCondition($condition = null) // Check condition type if (is_array($condition)) { - // Check if is numeric array if (array_keys($condition) === range(0, count($condition) - 1)) { - /* Numeric Array */ $query->where_in($this->_field($this->primaryKey), $condition); - } else { - /* Associated Array */ foreach ($condition as $field => $value) { - (is_array($value)) ? $query->where_in($field, $value) : $query->where($field, $value); } } @@ -1526,11 +1531,16 @@ protected function _findByCondition($condition = null) // Warning: This protection just simply check keywords that may not find out for some situations. $sql = $this->_dbr->get_compiled_select('', false); // No reset query // Check FROM for table condition - if (stripos($sql, 'from ') === false) + if (stripos($sql, 'from ') === false) { throw new Exception("You should find() first, or use condition array for update/delete", 400); + } // No condition situation needs to enable where protection - if (stripos($sql, 'where ') === false) - throw new Exception("You could not update/delete without any condition! Use find()->where('1=1') or condition array at least.", 400); + if (stripos($sql, 'where ') === false) { + throw new Exception( + "You could not update/delete without any condition! Use find()->where('1=1') or condition array at least.", + 400 + ); + } } return $query; @@ -1547,7 +1557,6 @@ protected function _findByCondition($condition = null) protected function _formatDate($field, &$attributes) { if ($this->timestamps && $field) { - switch ($this->dateFormat) { case 'datetime': $dateFormat = date("Y-m-d H:i:s"); @@ -1579,8 +1588,10 @@ protected function _addSoftDeletedCondition() $this->_withoutSoftDeletedScope = false; } elseif (static::SOFT_DELETED && isset($this->softDeletedFalseValue)) { // Add condition - $this->_dbr->where($this->_field(static::SOFT_DELETED), - $this->softDeletedFalseValue); + $this->_dbr->where( + $this->_field(static::SOFT_DELETED), + $this->softDeletedFalseValue + ); } return true; @@ -1598,7 +1609,6 @@ protected function _addGlobalScopeCondition() if ($this->_withoutGlobalScope) { // Reset Global Switch switch $this->_withoutGlobalScope = false; - } else { // Default to apply global scopes $this->_globalScopes(); @@ -1643,13 +1653,12 @@ private function _getDefaultDB() * ORM set property * * @param string $name Property key name - * @param mixed $value + * @param mixed $value */ public function __set($name, $value) { // Property check option if ($this->propertyCheck) { - $flag = false; // Check if exists @@ -1677,21 +1686,16 @@ public function __get($name) { // ORM property check if (array_key_exists($name, $this->_writeProperties)) { - return $this->_writeProperties[$name]; } elseif (array_key_exists($name, $this->_readProperties)) { - return $this->_readProperties[$name]; } // ORM relationship check elseif (method_exists($this, $method = $name)) { - return $this->_getRelationshipProperty($method); } // ORM schema check else { - // Write cache to read properties of this ORM foreach ($this->getTableSchema() as $key => $column) { - $this->_readProperties[$column['Field']] = isset($this->_readProperties[$column['Field']]) ? $this->_readProperties[$column['Field']] : null; @@ -1699,13 +1703,11 @@ public function __get($name) // Match property again if (array_key_exists($name, $this->_readProperties)) { - return $this->_readProperties[$name]; } // CI parent::__get() check if (property_exists(get_instance(), $name)) { - return parent::__get($name); } @@ -1725,15 +1727,11 @@ public function __get($name) */ public function __isset($name) { - if (isset($this->_writeProperties[$name])) { - return true; } elseif (isset($this->_readProperties[$name])) { - return true; } elseif (method_exists($this, $method = $name)) { - return ($this->_getRelationshipProperty($method)); } @@ -1749,7 +1747,6 @@ public function __isset($name) */ public function __unset($name) { - unset($this->_writeProperties[$name]); unset($this->_readProperties[$name]); } @@ -1758,13 +1755,12 @@ public function __unset($name) * ArrayAccess offsetSet * * @param string $offset - * @param mixed $value + * @param mixed $value * * @return void */ public function offsetSet($offset, $value) { - return $this->__set($offset, $value); } @@ -1777,7 +1773,6 @@ public function offsetSet($offset, $value) */ public function offsetExists($offset) { - return $this->__isset($offset); } @@ -1790,7 +1785,6 @@ public function offsetExists($offset) */ public function offsetUnset($offset) { - return $this->__unset($offset); } @@ -1803,7 +1797,6 @@ public function offsetUnset($offset) */ public function offsetGet($offset) { - return $this->$offset; } }