Skip to content

Instantly share code, notes, and snippets.

@brifiction
Created February 4, 2020 03:57
Show Gist options
  • Save brifiction/b7f8a570dc524b3773ff59a9e5768c90 to your computer and use it in GitHub Desktop.
Save brifiction/b7f8a570dc524b3773ff59a9e5768c90 to your computer and use it in GitHub Desktop.
Boolean Associative Array Example
<?php
namespace App\Helpers;
use App\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class FormHelper
{
/**
* Validate entire form input request and return a redirect, with message.
*
* The redirect is via route name below, in the return.
*
* @param Request $request
* @param string $redirect
* @param array $rules
* @param array $messages
* @param string $error
* @param string $success
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function validateFormInput(Request $request, string $redirect, array $rules, array $messages, string $error, string $success)
{
// validate entire form
$validator = validator($request->all(), $rules, $messages);
// return user to current form page, with validation errors
if ($validator->fails()) {
return redirect()
->route($redirect)
->withErrors($validator)
->withInput()
->with('error', $error);
} else {
return redirect()
->route($redirect)
->with('status', $success);
}
}
/**
* Get a validator for an incoming update / save information request.
*
* @param array $data
* @param array $rules
* @param array $messages
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data, array $rules, array $messages)
{
return Validator::make($data, $rules, $messages);
}
public function getAccountStatus($type)
{
try {
$data = Account::where('account_id', '=', auth()->user()->account->account_id)
->firstOrFail()
->toArray();
} catch (\Exception $e) {
$data = null;
}
return $this->getFormStatus($data);
}
public function getFormStatus($data)
{
// convert data into a collection
$data = collect($data);
// filter out timestamp properties
$data = $data->filter(function ($value, $key) {
return $key !== 'deleted_at';
})->all();
// create a boolean associative array
$booleanStack = [];
// check if collection is not empty / null
if (count($data) > 0) {
$keys = array_keys($data);
foreach ($keys as $key) {
// if any key exists, and its value is null
if (array_key_exists($key, $data) && (is_null($data[$key]) || empty($data[$key]))) {
$booleanStack += array($key => false);
} else {
$booleanStack += array($key => true);
}
}
}
// assign the first key, with its value
$result = reset($booleanStack);
// build, and sum up AND condition
foreach ($booleanStack as $key => $value) {
$result &= $value ? $value : 0;
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment