Skip to content

Instantly share code, notes, and snippets.

@MwirabuaTimothy
Last active June 20, 2016 07:15
Show Gist options
  • Save MwirabuaTimothy/c91000131be387b77ab8 to your computer and use it in GitHub Desktop.
Save MwirabuaTimothy/c91000131be387b77ab8 to your computer and use it in GitHub Desktop.
laravel helper functions
<?php
/**
* Return a success response
*
* @return Response
*/
function success($message, $redirectUrl, $record=null)
{
if($record){
if ( in_array('api', Request::segments())) {//for api
return [
'success' => true,
'version-code'=>Config::get('app.version-code'),
'whats-new'=>Config::get('app.whats-new'),
'minimum-version-code'=>Config::get('app.minimum-version-code'),
'minimum-whats-new'=>Config::get('app.minimum-whats-new'),
'message' => $message,
'record' => $record,
];
}
return Redirect::to($redirectUrl)->withInput()->withSuccess($message);
}
if ( in_array('api', Request::segments())) {//for api
return ['success' => true, 'message' => $message];
}
return Redirect::to($redirectUrl)->withInput()->withSuccess($message);
}
/**
* Return an error response
*
* @return Response
*/
function error($message, $redirectUrl=null, $message2=null, $key=null, $route_id=null)
{
if ( in_array('api', Request::segments())) {//for api
$response = ['success' => false, 'message' => $message];
if(isset($key)){
$response['key'] = $key;
}
return $response;
}
if($message2){
$message .= '<br/>'.$message2;
}
if($route_id){
return Redirect::route($redirectUrl, $route_id)->withInput()->withError($message);
}
if($redirectUrl){
return Redirect::to($redirectUrl)->withInput()->withError($message);
}
return $message;
}
function errorDie($message) {
header(sprintf("Content-Type: application/json"));
die(json_encode(error($message)));
}
/**
* Return validation errors
*
* @return Response
*/
function validator($validator, $redirectUrl=null)
{
if ( in_array('api', Request::segments())) {//for api
$array = $validator->messages()->toArray();
// return $array;
// new version:
$key = array_keys($array)[0];
$message = array_values($array)[0][0];
return error($message, $redirectUrl, null, $key);
// old version:
$output = [];
foreach ($array as $key=>$message){
$output[$key]= $message[0];
};
return ['success' => false, 'errors' => $output];
}
if (!$redirectUrl) { // setting the $redirectURL
$redirectUrl = URL::previous(); // falls back to home if referer is missing
}
return Redirect::to($redirectUrl)->withInput()->withErrors($validator); // special cases where you want to redirect elsewhere
// return Redirect::back()->withInput()->withErrors($validator);
function cached($record, $method, $param=null)
{
$key = get_class($record)."-$record->id-$method";
// if(Cache::has($key)){
// return Cache::get($key);
// }
$value = $record->$method($param);
Cache::forever($key, $value);
return $value;
}
function cachedIndex($record, $string)
{
$key = get_class($record)."-$record->id-$string";
if(Cache::has($key)){
return Cache::get($key);
}
$value = $record->$string;
Cache::forever($key, $value);
return $value;
}
function recache($record, $method, $param=null)
{
$key = get_class($record)."-$record->id-$method";
$value = $record->$method($param);
Cache::forever($key, $value);
}
function recacheIndex($record, $string)
{
$key = get_class($record)."-$record->id-$string";
$value = $record->$string;
Cache::forever($key, $value);
}
function toastr()
{
$types = ['success', 'warning', 'info', 'error', 'msg'];
foreach ($types as $type):
if (Session::get($type)):
$msg = Session::get($type);
if(is_array(json_decode($msg,true))):
$msg = implode('', $msg->all(':message<br/>'));
endif;
if ($type == 'danger') $type = 'error';
Session::put('toastr.level', $type);
Session::put('toastr.message', $msg);
endif;
endforeach;
if ($errors = Request::session()->get('errors')):
$msg = '';
foreach ($errors->all() as $error):
$msg .= $error.'<br/>';
endforeach;
Session::put('toastr.level', 'error');
Session::put('toastr.message', $msg);
endif;
}
function report($tracker, $exception=null, $subject='ShopOfficer Exceptions'){
// save message
// @todo
// fetch team
$recipients = Config::get('app.devs');
$dev = $recipients[0];
// whatsapp/slack team
try {
}
catch (Exception $exception){
}
// sms message
try {
(new SMS)->send($dev['phone'], 'team.report', [substr($tracker, 0, 160)]);
$message = 'Successfully sent sms!';
}
catch (Exception $exception){
$message = 'Failed to send sms!'.$tracker;
}
// email team
try {
$data = [
'body' => $tracker.'<br/>'.'<br/>'.$exception,
'name' => $dev['name'],
'email' => $dev['email'],
];
Mail::send('emails.simple', $data, function($message) use ($dev, $subject) {
$message->to([$dev['email'] => $dev['name']]);
$message->subject($subject);
});
$message .= '<br/> Successfully sent mail!';
return $message;
}
catch (Exception $exception){
$message .= '<br/> Failed to send mail!'.$tracker;
return $message;
}
}
function timestamp()
{
return substr(microtime(true) * 100, 0, 12);
}
function uploadImage($record, $field) {
if(Input::hasFile($field)) {
$file = Input::file($field);
$destinationPath = '/uploads/' . $record->getTable() . '/' . $field.'/'.$record->id.'/';
$extension = $file->getClientOriginalExtension();
$filename = timestamp() . '.' . $extension;
$uploadSuccess = $file->move(public_path() . $destinationPath, $filename);
return $destinationPath.$filename;
}
elseif(Input::get($field)) { // possible base64 upload
$data = explode(',', Input::get($field));
$decoded = base64_decode($data[1]);
$path = '/uploads/'.$record->getTable().'/'.$field.'/'.$record->id.'/';
$apath = public_path().$path;
$extension = 'png';
$filename = timestamp() . '.' . $extension;
$filename_path = $apath.$filename;
$folder = File::makeDirectory($apath, 493, true, true);
if (File::isDirectory($apath))
{
$bytes_written = File::put($filename_path, $decoded);
if ($bytes_written != false)
{
return $path.$filename;
}
}
}
else{
// return ''; // dont return null
return $record[$field]; // allow updates if they worked only
}
}
function getUpload($record, $field, $placeholder=null) {
$table = $record->getTable();
$id = $record->id;
$name = $record->$field;
if ($name):
return $name;
endif;
if ($placeholder):
return $placeholder;
endif;
return $name; // allowing blank images
$name = "no_$field.png";
return tempImage($table, $field);
}
function tempImage($table, $field) {
return asset("/assets/img/$table/$field/no_$field.png");
}
function getPlatform()
{
$ua = $_SERVER['HTTP_USER_AGENT'];
if(strpos($ua, 'MSIE') !== FALSE)
$name = 'Internet explorer';
elseif(strpos($ua, 'Trident') !== FALSE) //For Supporting IE 11
$name = 'Internet explorer';
elseif(strpos($ua, 'Firefox') !== FALSE)
$name = 'Mozilla Firefox';
elseif(strpos($ua, 'Chrome') !== FALSE)
$name = 'Google Chrome';
elseif(strpos($ua, 'Opera Mini') !== FALSE)
$name = "Opera Mini";
elseif(strpos($ua, 'Opera') !== FALSE)
$name = "Opera";
elseif(strpos($ua, 'Safari') !== FALSE)
$name = "Safari";
else
$name = 'Something else';
$ua = strtolower($ua);
// What version?
if (preg_match('/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/', $ua, $matches)) {
$version = $matches[1];
}
else {
$version = 'unknown';
}
// Running on what platform?
if (preg_match('/linux/', $ua)) {
$platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/', $ua)) {
$platform = 'osx';
}
elseif (preg_match('/windows|win32/', $ua)) {
$platform = 'windows';
}
else {
$platform = 'unrecognized';
}
return [
'browser' => $name,
'version' => $version,
'platform' => $platform,
'user_agent' => $ua
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment