public function saveMetaBox() { global $post; // Verify noncename if (!isset($_POST['noncename-' . $this->id]) || !wp_verify_nonce($_POST['noncename-' . $this->id], $this->id)) { return $post->ID; } // Authorized? if (!current_user_can('edit_post', $post->ID)) { return $post->ID; } // Prohibits saving data twice if ($post->post_type == 'revision') { return $post->ID; } foreach ($this->metaTemplate->getKeys() as $key) { $value = $_POST[$key]; if (is_array($value)) { $value = array_filter_recursive($value); } // If the value is defined as an array then serialize it if (empty($value)) { delete_post_meta($post->ID, $key); continue; } // Insert or update the db depending on if the value alredy exist get_post_meta($post->ID, $key) ? update_post_meta($post->ID, $key, $value) : add_post_meta($post->ID, $key, $value); } }
function unmagic() { if (get_magic_quotes_gpc()) { $_GET = array_filter_recursive($_GET, "stripslashes"); $_POST = array_filter_recursive($_POST, "stripslashes"); $_COOKIE = array_filter_recursive($_COOKIE, "stripslashes"); } }
public function testArrayFilterRecursive() { $array = array('User' => array('Profile' => array('user_id' => null, 'primary_email' => 'some value'), 'Roster' => array('user_id' => 1, 'id' => 0, 'roster_status_id' => 0, 'RosterStatus' => array('name' => 1)))); $result = array_filter_recursive($array); $expected = array('User' => array('Profile' => array('primary_email' => 'some value'), 'Roster' => array('user_id' => 1, 'RosterStatus' => array('name' => 1)))); $this->assertEqual($result, $expected); $this->assertEqual($array['User']['Profile']['user_id'], null); }
public static function ArrayFilterRecursive($data) { foreach ($data as &$value) { if (is_array($value)) { $value = array_filter_recursive($value); } } return array_filter($data); }
function array_filter_recursive($input) { foreach ($input as &$value) { if (is_array($value)) { $value = array_filter_recursive($value); } } return array_filter($input); }
function array_filter_recursive($input, $callback = null) { if (!is_array($input)) { return $input; } if (null === $callback) { $callback = function ($v) { return !empty($v); }; } $input = array_map(function ($v) use($callback) { return array_filter_recursive($v, $callback); }, $input); return array_filter($input, $callback); }
/** function array_filter_recursive * * Exactly the same as array_filter except this function * filters within multi-dimensional arrays * * @param array * @param string optional callback function name * @param bool optional flag removal of empty arrays after filtering * @return array merged array */ function array_filter_recursive($array, $callback = null, $remove_empty_arrays = false) { foreach ($array as $key => &$value) { // mind the reference if (is_array($value)) { $value = array_filter_recursive($value, $callback); if ($remove_empty_arrays && !(bool) $value) { unset($array[$key]); } } else { if (!is_null($callback) && !$callback($value)) { unset($array[$key]); } elseif (!(bool) $value) { unset($array[$key]); } } } unset($value); // kill the reference return $array; }
<?php require __DIR__ . '/../../vendor/autoload.php'; use opensrs\OMA\GetCompanyChanges; if ($_SERVER['REQUEST_METHOD'] === 'POST') { require_once dirname(__FILE__) . '/../../opensrs/openSRS_loader.php'; // Put the data to the Formatted array $callArray = array('company' => $_POST['company'], 'range' => array('first' => $_POST['first'], 'limit' => $_POST['limit'])); if (!empty($_POST['token'])) { $callArray['token'] = $_POST['token']; } // Open SRS Call -> Result $response = GetCompanyChanges::call(array_filter_recursive($callArray)); // Print out the results echo ' In: ' . json_encode($callArray) . '<br>'; echo 'Out: ' . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = 'json'; } ?> <?php include 'header.inc'; ?> <div class="container"> <h3>get_company_changes</h3> <form action="" method="post" class="form-horizontal" >
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Put the data to the Formatted array $callArray = array("user" => $_POST["user"], "attributes" => array("folder" => $_POST["folder"], "headers" => $_POST["headers"], "job" => $_POST["job"])); if (!empty($_POST["poll"])) { $callArray["attributes"]["poll"] = $_POST["poll"]; } if (!empty($_POST["token"])) { $callArray["token"] = $_POST["token"]; } // Open SRS Call -> Result require_once dirname(__FILE__) . "/../../opensrs/openSRS_loader.php"; $response = GetDeletedMessages::call(array_filter_recursive($callArray)); // Print out the results echo " In: " . json_encode($callArray) . "<br>"; echo "Out: " . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = "json"; } ?> <?php include "header.inc"; ?> <div class="container">
/** @see idbQuery::parse() */ public function parse($queryText, array $args = null) { // Преобразуем текст в нижний регистр //$query_text = mb_strtolower( $query_text, 'UTF-8' ); // Паттерн для определения метода динамического запроса $sortingPattern = ' /(?:^(?<method>find_by|find_all_by|all|first|last)_) |_order_by_ (?P<order>[a-zа-я0-9]+) _ (?P<order_dir>(?:asc|desc)) |_limit_ (?P<limit_start>\\d+) (?:_(?P<limit_end>\\d+))? |_group_by_(?P<group>.+) |_join_ (?<join>.+) /iux'; // Это внутренний счетчик для аргументов запроса для того чтобы не сбиться при их подставлении // в условие запроса к БД $argsCnt = 0; // Выполним первоначальный парсинг проверяющий правильность указанного метода // выборки данных и поиск возможных модификаторов запроса if (preg_match_all($sortingPattern, $queryText, $globalMatches)) { // Удалим все пустые группы полученные послке разпознования $globalMatches = array_filter_recursive($globalMatches); // Получим текст условий самого запроса, убрав из него все возможные модификаторы и параметры // и переберем только полученные группы условий запроса foreach (explode('_or_', str_ireplace($globalMatches[0], '', $queryText)) as $groupText) { // Добавим группу условий к запросу $this->or_('AND'); // Переберем поля которые формируют условия запроса - создание объекты-условия запроса foreach (explode('_and_', $groupText) as $conditionText) { $this->cond($conditionText, $args[$argsCnt++]); } } // Получим сортировку запроса if (isset($globalMatches['order'])) { $this->order = array($globalMatches['order'][0], $globalMatches['order_dir'][0]); } // Получим ограничения запроса if (isset($globalMatches['limit_start'])) { $this->limit = array($globalMatches['limit_start'][0], $globalMatches['limit_end'][0]); } // Получим групировку запроса if (isset($globalMatches['group'])) { $this->group = explode('_and_', $globalMatches['group'][0]); } // Получим имена таблиц для "объединения" в запросе if (isset($globalMatches['join'])) { foreach (explode('_and_', $globalMatches['join'][0]) as $join) { $this->join($join); } } } // Вернем полученный объект-запрос return $this; }
/** * Displays a roster list * * ### Passed args: * - integer $Involvement The id of the involvement to filter for * - integer $User The id of the user to filter for * * @todo place user list limit into involvement() */ public function index() { $conditions = array(); $userConditions = array(); $involvementId = $this->passedArgs['Involvement']; $involvement = $this->Roster->Involvement->find('first', array('fields' => array('roster_visible', 'ministry_id', 'take_payment'), 'conditions' => array('Involvement.id' => $involvementId), 'contain' => array('Ministry' => array('fields' => array('campus_id'))))); $roster = $this->Roster->find('first', array('fields' => array('roster_status_id'), 'conditions' => array('user_id' => $this->activeUser['User']['id'], 'involvement_id' => $involvementId), 'contain' => false)); $inRoster = !empty($roster); $fullAccess = $this->Roster->Involvement->isLeader($this->activeUser['User']['id'], $involvementId) || $this->Roster->Involvement->Ministry->isManager($this->activeUser['User']['id'], $involvement['Involvement']['ministry_id']) || $this->Roster->Involvement->Ministry->Campus->isManager($this->activeUser['User']['id'], $involvement['Ministry']['campus_id']) || $this->isAuthorized('rosters/index', array('Involvement' => $involvementId)); $canSeeRoster = $inRoster && $roster['Roster']['roster_status_id'] == 1 && $involvement['Involvement']['roster_visible'] || $fullAccess; if (!$canSeeRoster) { $this->cakeError('privateItem', array('type' => 'Roster')); } // if involvement is defined, show just that involvement $conditions['Roster.involvement_id'] = $involvementId; if (!empty($this->data)) { $filters = $this->data['Filter']; if (isset($filters['User']['active'])) { if ($filters['User']['active'] !== '') { $conditions += array('User.active' => $filters['User']['active']); } } if (isset($filters['Roster']['show_childcare'])) { if ($filters['Roster']['show_childcare']) { $conditions += array('Roster.parent_id >' => 0); } unset($filters['Roster']['show_childcare']); } if (isset($filters['Roster']['hide_childcare'])) { if ($filters['Roster']['hide_childcare']) { $conditions += array('Roster.parent_id' => null); } unset($filters['Roster']['hide_childcare']); } unset($filters['Role']); $filters = array_filter_recursive($filters); $conditions += $this->postConditions($filters, 'LIKE'); if (isset($this->data['Filter']['Role'])) { $conditions += $this->Roster->parseCriteria(array('roles' => $this->data['Filter']['Role'])); } } else { $this->data = array('Filter' => array('Roster' => array('pending' => 0), 'Role' => array())); } $link = array('User' => array('fields' => array('id', 'username', 'active', 'flagged'), 'Profile' => array('fields' => array('first_name', 'last_name', 'name', 'cell_phone', 'allow_sponsorage', 'primary_email', 'background_check_complete'))), 'RosterStatus' => array('fields' => array('name'))); $contain = array('Role'); $this->Roster->recursive = -1; $fields = array('id', 'created', 'user_id', 'parent_id'); if ($involvement['Involvement']['take_payment']) { array_push($fields, 'amount_due', 'amount_paid', 'balance'); } $this->paginate = compact('conditions', 'link', 'contain', 'fields'); // save search for multi select actions $this->MultiSelect->saveSearch($this->paginate); // set based on criteria $this->Roster->Involvement->contain(array('InvolvementType', 'Leader')); $involvement = $this->Roster->Involvement->read(null, $involvementId); $rosters = $this->FilterPagination->paginate(); $rosterIds = Set::extract('/Roster/id', $rosters); $counts['childcare'] = $this->Roster->find('count', array('conditions' => $conditions + array('Roster.parent_id >' => 0), 'link' => $link)); $counts['pending'] = $this->Roster->find('count', array('conditions' => $conditions + array('Roster.roster_status_id' => 2), 'link' => $link)); $counts['leaders'] = count($involvement['Leader']); $counts['confirmed'] = $this->Roster->find('count', array('conditions' => $conditions + array('Roster.roster_status_id' => 1), 'link' => $link)); $counts['total'] = $this->params['paging']['Roster']['count']; $roles = $this->Roster->Involvement->Ministry->Role->find('list', array('conditions' => array('Role.id' => $this->Roster->Involvement->Ministry->Role->findRoles($involvement['Involvement']['ministry_id'])))); $rosterStatuses = $this->Roster->RosterStatus->find('list'); $this->set(compact('rosters', 'involvement', 'rosterIds', 'rosterStatuses', 'counts', 'roles', 'fullAccess')); }
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Put the data to the Formatted array $callArray = array("criteria" => array("company" => $_POST["company"], "match" => $_POST["match"]), "range" => array("first" => $_POST["first"], "limit" => $_POST["limit"]), "sort" => array("by" => $_POST["by"], "direction" => $_POST["direction"])); if (!empty($_POST["deleted"])) { $callArray["criteria"]["deleted"] = true; } if (!empty($_POST["type"])) { $callArray["criteria"]["type"] = explode(",", $_POST["type"]); } if (!empty($_POST["token"])) { $callArray["token"] = $_POST["token"]; } // Open SRS Call -> Result require_once dirname(__FILE__) . "/../../opensrs/openSRS_loader.php"; $response = SearchDomains::call(array_filter_recursive($callArray)); // Print out the results echo " In: " . json_encode($callArray) . "<br>"; echo "Out: " . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = "json"; } include "header.inc"; ?> <div class="container"> <h3>search_domains</h3> <form action="" method="post" class="form-horizontal" >
/** * Выполнить рекурсивную очистку массива от незаполненый ключей * с его последующей перенумерацией. * * @param array $input Массив для рекурсивной очистки и перенумерации * * @return array Перенумерованный очищеный массив */ function array_filter_recursive(array &$input) { // Переберем полученный массив // Используем foreach потому что незнаем какой массив // имеет ли он ключи или только нумерацию foreach ($input as &$value) { // Если это подмассив if (is_array($value)) { // Выполним углубление в рекурсию и перенумерируем полученный "очищенный" массив $value = array_values(array_filter_recursive($value)); } } // Выполним фильтрацию массива от пустых значений return array_filter($input); }
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Put the data to the Formatted array $callArray = array("company" => $_POST["company"], "bulletin" => $_POST["bulletin"], "type" => $_POST["type"], "test_email" => $_POST["test_email"]); if (!empty($_POST["token"])) { $callArray["token"] = $_POST["token"]; } // Open SRS Call -> Result require_once dirname(__FILE__) . "/../../opensrs/openSRS_loader.php"; $response = PostCompanyBulletin::call(array_filter_recursive($callArray)); // Print out the results echo " In: " . json_encode($callArray) . "<br>"; echo "Out: " . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = "json"; } ?> <?php include "header.inc"; ?> <div class="container"> <h3>post_company_bulletin</h3> <form action="" method="post" class="form-horizontal" > <div class="control-group"> <label class="control-label">Session Token (Option)</label>
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Put the data to the Formatted array $callArray = array("criteria" => array("domain" => $_POST["domain"], "match" => $_POST["match"]), "range" => array("first" => $_POST["first"], "limit" => $_POST["limit"]), "sort" => array("by" => $_POST["by"], "direction" => $_POST["direction"])); if (!empty($_POST["token"])) { $callArray["token"] = $_POST["token"]; } // Open SRS Call -> Result require_once dirname(__FILE__) . "/../../opensrs/openSRS_loader.php"; $response = SearchWorkgroups::call(array_filter_recursive($callArray)); // Print out the results echo " In: " . json_encode($callArray) . "<br>"; echo "Out: " . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = "json"; } include "header.inc"; ?> <div class="container"> <h3>search_workgroups</h3> <form action="" method="post" class="form-horizontal" > <div class="control-group"> <label class="control-label">Session Token (Option)</label> <div class="controls"><input type="text" name="token" value="" ></div> </div> <h4>Required</h4>
<?php require __DIR__ . '/../../vendor/autoload.php'; use opensrs\OMA\ChangeCompany; if ($_SERVER['REQUEST_METHOD'] === 'POST') { require_once dirname(__FILE__) . '/../../opensrs/openSRS_loader.php'; // Put the data to the Formatted array $callArray = array('company' => $_POST['user'], 'attributes' => array('password' => $_POST['password'], 'spamtag' => $_POST['spamtag'], 'allow' => explode(',', $_POST['allow']), 'block' => explode(',', $_POST['block']))); if (!empty($_POST['token'])) { $callArray['token'] = $_POST['token']; } // Open SRS Call -> Result $response = ChangeCompany::call(array_filter_recursive($callArray)); // Print out the results echo ' In: ' . json_encode($callArray) . '<br>'; echo 'Out: ' . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = 'json'; } ?> <?php include 'header.inc'; ?> <div class="container"> <h3>change_company</h3>
/** * Creates a find options array from post data. If the POSTed data has fields * from this model, they will be added to this model's `fields` list. If it has * other models, it will create a contain array with those models and their fields. * * Use in conjunction with Controller::postConditions() to make search forms super-quick! * * @param array $data The Cake post data * @param Model $Model The model * @param string $foreignKey A foreign key for the association to include * @return array The options array */ public function postOptions($data, $Model = null, $foreignKey = null) { // get associated models $first = false; if (!$Model) { $first = true; $Model = $this; $data = array_filter_recursive($data); } $associated = $Model->getAssociated(); $options = $data; if ($foreignKey) { $options['fields'][] = $foreignKey; } foreach ($data as $model => $field) { if ($Model->hasField($model, true)) { // add to fields array if it's a field if ($Model->isVirtualField($model)) { $options['fields'][] = $Model->getVirtualField($model) . ' AS ' . $Model->alias . '__' . $model; } else { $options['fields'][] = $model; } unset($options[$model]); } elseif ($Model->alias === $model) { foreach ($field as $f => $v) { $options['fields'][] = $f; } unset($options[$model]); } elseif (array_key_exists($model, $associated)) { // check for habtm [Publication][Publication][0] = 1 if ($model == array_shift(array_keys($field))) { $field = array(); } // recusively check for more models to contain $foreignKey = null; if (in_array($associated[$model], array('hasOne', 'hasMany'))) { $foreignKey = $Model->{$associated[$model]}[$model]['foreignKey']; } elseif ($associated[$model] == 'belongsTo') { $options['fields'][] = $Model->primaryKey; $options['fields'][] = $Model->{$associated[$model]}[$model]['foreignKey']; } if ($first) { $options['contain'][$model] = $this->postOptions($field, $Model->{$model}, $foreignKey); unset($options[$model]); } else { $options[$model] = $this->postOptions($field, $Model->{$model}, $foreignKey); } } else { // completely unrelated unset($options[$model]); } } return $options; }
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Put the data to the Formatted array $callArray = array("domain" => $_POST["domain"], "bulletin" => $_POST["bulletin"], "type" => explode(",", $_POST["type"]), "test_email" => $_POST["test_email"]); if (!empty($_POST["token"])) { $callArray["token"] = $_POST["token"]; } // Open SRS Call -> Result require_once dirname(__FILE__) . "/../../opensrs/openSRS_loader.php"; $response = PostDomainBulletin::call(array_filter_recursive($callArray)); // Print out the results echo " In: " . json_encode($callArray) . "<br>"; echo "Out: " . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = "json"; } ?> <?php include "header.inc"; ?> <div class="container"> <h3>post_domain_bulletin</h3> <form action="" method="post" class="form-horizontal" > <div class="control-group"> <label class="control-label">Session Token (Option)</label>
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Put the data to the Formatted array $callArray = array("domain" => $_POST["domain"], "range" => array("first" => $_POST["first"], "limit" => $_POST["limit"])); if (!empty($_POST["token"])) { $callArray["token"] = $_POST["token"]; } // Open SRS Call -> Result require_once dirname(__FILE__) . "/../../opensrs/openSRS_loader.php"; $response = GetDomainChanges::call(array_filter_recursive($callArray)); // Print out the results echo " In: " . json_encode($callArray) . "<br>"; echo "Out: " . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = "json"; } ?> <?php include "header.inc"; ?> <div class="container"> <h3>get_domain_changes</h3> <form action="" method="post" class="form-horizontal" > <div class="control-group"> <label class="control-label">Session Token (Option)</label>
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Put the data to the Formatted array $callArray = array("user" => $_POST["user"], "range" => array("first" => $_POST["first"], "limit" => $_POST["limit"])); if (!empty($_POST["token"])) { $callArray["token"] = $_POST["token"]; } // Open SRS Call -> Result require_once dirname(__FILE__) . "/../../opensrs/openSRS_loader.php"; $response = GetUserChanges::call(array_filter_recursive($callArray)); // Print out the results echo " In: " . json_encode($callArray) . "<br>"; echo "Out: " . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = "json"; } ?> <?php include "header.inc"; ?> <div class="container"> <h3>get_user_changes</h3> <form action="" method="post" class="form-horizontal" > <div class="control-group"> <label class="control-label">Session Token (Option)</label>
<?php require __DIR__ . '/../../vendor/autoload.php'; use opensrs\OMA\ChangeDomain; if ($_SERVER['REQUEST_METHOD'] === 'POST') { require_once dirname(__FILE__) . '/../../opensrs/openSRS_loader.php'; // Put the data to the Formatted array $callArray = array('domain' => $_POST['domain'], 'attributes' => array('timezone' => $_POST['timezone'], 'language' => $_POST['language'], 'filtermx' => $_POST['filtermx'], 'spam_tag' => $_POST['spam_tag'], 'spam_folder' => $_POST['spam_folder'], 'spam_level' => $_POST['spam_level'])); if (!empty($_POST['token'])) { $callArray['token'] = $_POST['token']; } // Open SRS Call -> Result $response = ChangeDomain::call(array_filter_recursive($callArray)); // Print out the results echo ' In: ' . json_encode($callArray) . '<br>'; echo 'Out: ' . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = 'json'; } ?> <?php include 'header.inc'; ?> <div class="container"> <h3>change_domain</h3> <form action="" method="post" class="form-horizontal" >
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Put the data to the Formatted array $callArray = array("user" => $_POST["user"], "attributes" => array("name" => $_POST["name"], "password" => $_POST["password"], "delivery_forward" => $_POST["delivery_forward"], "forward_recipients" => $_POST["forward_recipients"], "spamtag" => $_POST["spamtag"], "autoresponder" => "TEST Auto responder", "allow" => explode(",", $_POST["allow"]), "block" => explode(",", $_POST["block"])), "create_only" => $_POST["create_only"] ? true : false); if (!empty($_POST["token"])) { $callArray["token"] = $_POST["token"]; } // Open SRS Call -> Result require_once dirname(__FILE__) . "/../../opensrs/openSRS_loader.php"; $response = ChangeUser::call(array_filter_recursive($callArray)); // Print out the results echo " In: " . json_encode($callArray) . "<br>"; echo "Out: " . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = "json"; } ?> <?php include "header.inc"; ?> <div class="container"> <h3>change_user</h3> <form action="" method="post" class="form-horizontal" > <div class="control-group">
/** * Array_Filter for multi-dimensional arrays. * * @param array $array Untouched Array. * @param function $callback Function to Apply to Each Element. * @return array Filtered Array. */ function array_filter_recursive($array, $callback = null) { foreach ($array as $key => &$value) { if (is_array($value)) { $value = array_filter_recursive($value, $callback); } else { if (!is_null($callback)) { if (!$callback($value)) { unset($array[$key]); } } else { if (!(bool) $value) { unset($array[$key]); } } } } unset($value); return $array; }
<?php require __DIR__ . '/../../vendor/autoload.php'; use opensrs\OMA\SearchUsers; if ($_SERVER['REQUEST_METHOD'] === 'POST') { require_once dirname(__FILE__) . '/../../opensrs/openSRS_loader.php'; // Put the data to the Formatted array $callArray = array('criteria' => array('domain' => $_POST['domain'], 'workgroup' => $_POST['workgroup'], 'match' => $_POST['match'], 'deleted' => $_POST['deleted'] ? true : false), 'range' => array('first' => $_POST['first'], 'limit' => $_POST['limit']), 'sort' => array('by' => $_POST['by'], 'direction' => $_POST['direction'])); if (!empty($_POST['type'])) { $callArray['criteria']['type'] = explode(',', $_POST['type']); } if (!empty($_POST['token'])) { $callArray['token'] = $_POST['token']; } // Open SRS Call -> Result $response = SearchUsers::call(array_filter_recursive($callArray)); // Print out the results echo ' In: ' . json_encode($callArray) . '<br>'; echo 'Out: ' . $response; } else { // Format if (isset($_GET['format'])) { $tf = $_GET['format']; } else { $tf = 'json'; } include 'header.inc'; ?> <div class="container"> <h3>search_users</h3> <form action="" method="post" class="form-horizontal" >
/** * @param type $project * @param type $section * @param type $answers * @param type $incident_id * @param type $resultable * @param type $resultable_type * @return type * @throws GeneralException */ private function saveResults($project, $section, $raw_answers, $incident_id, $resultable, $resultable_type) { // this function defined in app\helpers.php $answers = array_filter_recursive($raw_answers); /** * Result is link between questions,location,paricipants and actual answer * mark the status * Results table is polymophic table between Participants, Locations and Results */ $result = Result::firstOrNew(['section_id' => $section, 'project_id' => $project->id, 'incident_id' => $incident_id, 'resultable_id' => $resultable->id, 'resultable_type' => $resultable_type]); if ($incident_id) { $result->incident_id = $incident_id; } $result->resultable_id = $resultable->id; $result->results = $answers; $result->section_id = $section; $current_user = auth()->user(); $result->user()->associate($current_user); $result->project()->associate($project); if (isset($resultable)) { $result->resultable()->associate($resultable); } if (!empty($answers)) { $result->information = $this->updateStatus($project, $section, $answers, $incident_id, $resultable, $resultable_type); if ($result->save()) { /** * Save actual answers after result status saved * delete all related answers before save. * More like overwriting old answers */ Answers::where('status_id', $result->id)->delete(); foreach ($answers as $qslug => $ans) { $q = $this->questions->getQuestionByQnum($qslug, $section, $project->id); foreach ($ans as $akey => $aval) { if ($akey == 'radio') { $answerkey = $aval; } else { $answerkey = $akey; } $qanswer = $q->qanswers->where('slug', $answerkey)->first(); if (!is_null($qanswer)) { if (in_array($qanswer->type, ['radio', 'checkbox'])) { $answerVal = $qanswer->value; } else { $answerVal = $aval; } $answerR = Answers::firstOrNew(['qid' => $q->id, 'akey' => $answerkey, 'status_id' => $result->id]); if (isset($answerVal) && !empty($answerVal)) { $answerR->value = $answerVal; $result->answers()->save($answerR); } } } } return $result; } } }