Skip to content

Instantly share code, notes, and snippets.

@dacastro4
Created December 19, 2018 18:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dacastro4/09478a64382d09ec5986049239e25dd5 to your computer and use it in GitHub Desktop.
Save dacastro4/09478a64382d09ec5986049239e25dd5 to your computer and use it in GitHub Desktop.
Laravel 5 Helper Methods (PHP 7+)
<?php
/**
* Created by PhpStorm.
* User: danielcastro
* Date: 2/2/17
* Time: 2:06 PM
*
* Place under app/paht/to/file folder and add
* "files" : [
* "app/paht/to/file/helpers.php"
* ]
* to your composer autoload and run composer dumpautoload
*
* Method getCoordsFromZip requires a lookup
* Method curl_google_maps requires an ENV variable GOOGLE_MAPS_API_KEY
* Method sentry_report requires composer package "sentry/sentry-laravel"
*/
use Symfony\Component\VarDumper\VarDumper;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
if ( !function_exists('is_production') ) {
/**
* Returns if the app is in Production
*
* @return int
*/
function is_production()
{
return app()->environment() === 'production';
}
}
if ( !function_exists('clean_number') ) {
/**
* Strips all non-numeric characters from phone number
*
* @param $phoneNumber
*
* @return bool|string
*/
function clean_number( $phoneNumber )
{
$phoneNumber = preg_replace("/\D/", "", $phoneNumber);
return substr($phoneNumber, -10);
}
}
if ( !function_exists('two_decimals') ) {
/**
* @param $number
* @return int
*/
function two_decimals( $number )
{
return number_format((float) $number, 2, '.', '');
}
}
if ( !function_exists('clean_value') ) {
/**
* @param $number
* @return int
*/
function clean_value( $number )
{
return str_replace(',', '', $number);
}
}
if ( !function_exists('dollars_to_cents') ) {
/**
* Take a float number an return the same value * 100. 100.00 -> 1000
*
* @param $float
* @return int
*/
function dollars_to_cents( $float )
{
return intval(float_multiply($float));
}
}
if ( !function_exists('cents_to_dollars') ) {
/**
* Take an integer and converts it to float rounded to two digits 1000 -> 100.00
*
* @param $int
* @return float
*/
function cents_to_dollars( $int )
{
return floatval($int / 100);
}
}
if ( !function_exists('float_multiply') ) {
/**
* Take a float number an return the casted number to float rounded with two digits
*
* @param $integer
* @param int $_scale
* @return float
*/
function float_multiply( $integer, $_scale = 2 )
{
return roundfloat($integer * 100, $_scale);
}
}
if ( !function_exists('currency_format') ) {
function currency_format( $value, $format = '%.2n', $country = 'en_US', $locale = 'en_US.utf8' )
{
setlocale(LC_MONETARY, $country, $locale);
return money_format($format, $value);
}
}
if ( !function_exists('dollar_format') ) {
/**
*
* @param $amount
* @param string $format
* @return string
*/
function dollar_format( $amount, $format = "$%.2n" )
{
return money_format($format, $amount);
}
}
if ( !function_exists('roundfloat') ) {
/**
* Take a float number an return the casted number to float rounded to two digits
*
* @param $number
* @param int $round
* @return float
*/
function roundfloat( $number, $round = 2 )
{
$rounded = pow(10, $round);
return ceil(( floatval($number) * $rounded )) / $rounded;
}
}
if ( !function_exists('tax_rate') ) {
/**
* Take a float number an return the casted number to float rounded to two digits
*
* @param $price
* @param $tax
* @param int $quantity
* @return float
*/
function tax_rate( $price, $tax, $quantity = 1 )
{
$taxRate = $tax / 100;
$taxOperation = ( $price * $taxRate ) * $quantity;
return roundfloat($taxOperation);
}
}
if ( !function_exists('d') ) {
/**
* Dump the passed variables and end the script.
*
* @param $var
* @param array $moreVars
* @return void
*/
function d( $var, ...$moreVars )
{
VarDumper::dump($var);
foreach ( $moreVars as $v ) {
VarDumper::dump($v);
}
}
}
if ( !function_exists('trace') ) {
function trace( $msg, $die = false )
{
$s = print_r($msg, true);
$s .= "\n";
error_log($s, 3, storage_path("logs/trace.log"));
if ( $die ) {
echo( '<pre>' );
print_r($s);
echo( '</pre>' );
}
}
}
if ( !function_exists('array_to_object') ) {
/**
* Dump the passed variables and end the script.
*
* @param array $array
* @return object
*/
function array_to_object( $array )
{
return json_decode(json_encode($array));
}
}
if ( !function_exists('coords_from_zip') ) {
/**
* @param $zipcode
* @param bool $useCache
* @return array
*/
function coords_from_zip( $zipcode, $useCache = true )
{
$fallback = false;
if ( $useCache ) {
$zipcodes = Cache::rememberForever('lookup-table', function () {
return DB::table('lookup')->get();
});
$lookup = $zipcodes->where('zip', $zipcode)->first();
} else {
$lookup = DB::table('lookup')->where('zip', $zipcode)->first();
}
if ( $lookup ) {
$coords['latitude'] = $lookup->lat;
$coords['longitude'] = $lookup->lng;
} else {
$fallback = true;
}
if ( $fallback ) {
$coords = [];
$http_response = curl_google_maps($zipcode);
if ( $http_response['http_code'] == 200 ) {
$body = json_decode($http_response['body']);
if ( $body->status == 'ZERO_RESULTS' ) {
//no results
}
if ( isset($body->results[0]) ) {
$result = $body->results[0];
foreach ( $result->address_components as $component ) {
$types = $component->types;
switch ( $types ) {
case in_array('postal_code', $types):
{
$data['zip'] = $component->long_name;
break;
}
case in_array('locality', $types):
{
$data['city'] = $component->long_name;
break;
}
case in_array('administrative_area_level_2', $types):
{
$data['county'] = $component->long_name;
break;
}
case in_array('administrative_area_level_1', $types):
{
$data['state'] = $component->long_name;
break;
}
case in_array('country', $types):
{
$data['country'] = $component->short_name;
break;
}
}
}
$geo = $result->geometry->location;
$data['lng'] = $geo->lng;
$data['lat'] = $geo->lat;
DB::table('lookup')->insert($data);
$coords['latitude'] = $geo->lat;
$coords['longitude'] = $geo->lng;
} else {
$coords['latitude'] = null;
$coords['longitude'] = null;
}
}
}
if ( !isset($coords['latitude']) || !isset($coords['longitude']) ) {
$coords['latitude'] = 0;
$coords['longitude'] = 0;
}
return $coords;
}
}
if ( !function_exists('zip_code_from') ) {
/**
* @param $zipcode
* @param array $countries
* @return mixed
* @throws Exception
*/
function zip_code_from( $zipcode, $countries = [] )
{
$fallback = false;
$countries = count($countries) ? $countries : explode(',', env('COUNTRY_ZIPCODES', "US"));
$zipcodes = Cache::rememberForever('lookup-table', function () {
return DB::table('lookup')->get();
});
$lookup = $zipcodes->where('zip', $zipcode)->first();
if ( $lookup ) {
return in_array($lookup->country, $countries);
} else {
$fallback = true;
}
if ( $fallback ) {
$http_response = curl_google_maps($zipcode);
if ( $http_response['http_code'] == 200 ) {
$body = json_decode($http_response['body']);
if ( $body->status == 'ZERO_RESULTS' ) {
throw new Exception('Invalid Zip Code');
}
if ( isset($body->results[0]) ) {
$result = $body->results[0];
$country = "";
foreach ( $result->address_components as $component ) {
$types = $component->types;
if ( in_array('country', $types) ) {
$country = $component->short_name;
break;
}
}
if ( in_array($country, $countries) ) {
return true;
} else {
$cnts = implode(',', $countries);
throw new Exception("Currently accepting zip codes from {$cnts}");
}
}
throw new Exception('Invalid Zip Code');
}
}
}
}
if ( !function_exists('curl_google_maps') ) {
/**
* @param $address
* @return array
*/
function curl_google_maps( $address )
{
$ch = curl_init();
$googleApiKey = env('GOOGLE_MAPS_API_KEY', null);
$key = $googleApiKey ? "&key={$googleApiKey}" : null;
curl_setopt($ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&result_type=postal_code&sensor=true{$key}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/text',
'Accept: application/json',
]);
$http_response = array();
$http_response['body'] = curl_exec($ch);
$head = curl_getinfo($ch);
$http_response['http_code'] = $head['http_code'];
return $http_response;
}
}
if ( !function_exists('get_timezones') ) {
/**
* @return array
*/
function get_timezones()
{
$tz = [
"America/Los_Angeles" => "(GMT -07:00) America/Los_Angeles",
"America/Phoenix" => "(GMT -07:00) America/Phoenix",
"America/Denver" => "(GMT -06:00) America/Denver",
"America/Chicago" => "(GMT -05:00) America/Chicago",
"America/Indiana/Indianapolis" => "(GMT -04:00) America/Indiana/Indianapolis",
"America/Indiana/Petersburg" => "(GMT -04:00) America/Indiana/Petersburg",
"America/Puerto_Rico" => "(GMT -04:00) America/Puerto_Rico",
"America/Indianapolis" => "(GMT -04:00) America/Indianapolis",
"America/Santo_Domingo" => "(GMT -04:00) America/Santo_Domingo",
"America/Kentucky/Louisville" => "(GMT -04:00) America/Kentucky/Louisville",
"America/Kentucky/Monticello" => "(GMT -04:00) America/Kentucky/Monticello",
"America/Detroit" => "(GMT -04:00) America/Detroit",
"America/Dominica" => "(GMT -04:00) America/Dominica",
"America/Louisville" => "(GMT -04:00) America/Louisville",
"America/New_York" => "(GMT -04:00) America/New_York",
];
asort($tz);
return $tz;
}
}
if ( !function_exists('google_maps_location') ) {
/**
* @param $address
* @return string
*/
function google_maps_location( $address )
{
$address = str_replace(' ', '+', $address);
return "https://www.google.com/maps/search/{$address}/";
}
}
if ( !function_exists('distance_between_to_points') ) {
/**
* @param $latitudeFrom
* @param $longitudeFrom
* @param $latitudeTo
* @param $longitudeTo
* @param int $earthRadius
* @return float
*/
function distance_between_to_points( $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 3959 )
{
// convert from degrees to radians
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
return roundfloat($angle * $earthRadius);
}
}
if ( !function_exists('error') ) {
/**
* Write some error to the log.
*
* @param string $message
* @param array $context
*/
function error( $message, $context = [] )
{
return app('log')->error($message, $context);
}
}
if ( !function_exists('get_states') ) {
function get_states()
{
return [
'AL' => 'ALABAMA',
'AK' => 'ALASKA',
'AS' => 'AMERICAN SAMOA',
'AZ' => 'ARIZONA',
'AR' => 'ARKANSAS',
'CA' => 'CALIFORNIA',
'CO' => 'COLORADO',
'CT' => 'CONNECTICUT',
'DE' => 'DELAWARE',
'DC' => 'DISTRICT OF COLUMBIA',
'FM' => 'FEDERATED STATES OF MICRONESIA',
'FL' => 'FLORIDA',
'GA' => 'GEORGIA',
'GU' => 'GUAM GU',
'HI' => 'HAWAII',
'ID' => 'IDAHO',
'IL' => 'ILLINOIS',
'IN' => 'INDIANA',
'IA' => 'IOWA',
'KS' => 'KANSAS',
'KY' => 'KENTUCKY',
'LA' => 'LOUISIANA',
'ME' => 'MAINE',
'MH' => 'MARSHALL ISLANDS',
'MD' => 'MARYLAND',
'MA' => 'MASSACHUSETTS',
'MI' => 'MICHIGAN',
'MN' => 'MINNESOTA',
'MS' => 'MISSISSIPPI',
'MO' => 'MISSOURI',
'MT' => 'MONTANA',
'NE' => 'NEBRASKA',
'NV' => 'NEVADA',
'NH' => 'NEW HAMPSHIRE',
'NJ' => 'NEW JERSEY',
'NM' => 'NEW MEXICO',
'NY' => 'NEW YORK',
'NC' => 'NORTH CAROLINA',
'ND' => 'NORTH DAKOTA',
'MP' => 'NORTHERN MARIANA ISLANDS',
'OH' => 'OHIO',
'OK' => 'OKLAHOMA',
'OR' => 'OREGON',
'PW' => 'PALAU',
'PA' => 'PENNSYLVANIA',
'PR' => 'PUERTO RICO',
'RI' => 'RHODE ISLAND',
'SC' => 'SOUTH CAROLINA',
'SD' => 'SOUTH DAKOTA',
'TN' => 'TENNESSEE',
'TX' => 'TEXAS',
'UT' => 'UTAH',
'VT' => 'VERMONT',
'VI' => 'VIRGIN ISLANDS',
'VA' => 'VIRGINIA',
'WA' => 'WASHINGTON',
'WV' => 'WEST VIRGINIA',
'WI' => 'WISCONSIN',
'WY' => 'WYOMING',
];
}
}
if ( !function_exists('get_locale') ) {
function get_locale()
{
return request('lang') ?? app()->getLocale();
}
}
if ( !function_exists('parse') ) {
/**
* @param $value
* @return \Carbon\Carbon
*/
function parse( $value )
{
return \Carbon\Carbon::parse($value);
}
}
if ( !function_exists('display_array') ) {
/**
* @param $value
* @return string
*/
function display_array( $value )
{
if ( is_array($value) ) {
return implode(', ', $value);
}
return $value;
}
}
if ( !function_exists('sentry_report') ) {
/**
* Sends an error to Sentry
*
*
* I'll be back
*
*
* @param $message
* @param $exception
* @param null $user
* @param string $level
* @param array $extra
* @return string
*/
function sentry_report( $message, $exception, $user = null, $level = 'error', $extra = [] )
{
app('sentry')->captureMessage($message, [], [
'user' => $user ?? auth()->id(),
'extra' => array_merge($extra, [
'exception' => $exception->getMessage(),
'line' => $exception->getLine(),
'code' => $exception->getCode(),
'file' => $exception->getFile(),
]),
'level' => $level,
]);
}
}
if ( !function_exists('array_search_multi') ) {
/**
* Searches in multi dimensional array
* @param mixed $needle
* @param array $haystack
* @param bool $strict
* @return bool
*/
function array_search_multi( $needle, $haystack = [], $strict = false )
{
foreach ( $haystack as $key => $items ) {
foreach ( $items as $item ) {
if ( $strict ) {
if ( $item === $needle )
return $key;
} else {
if ( $item == $needle )
return $key;
}
}
}
return false;
}
}
if ( !function_exists('array_count') ) {
/**
* @param array $array
* @param int $count
* @return int
*/
function array_count( array $array = [], $count = 0 )
{
$internalCount = 0 | $count;
foreach ( $array as $key => $items ) {
if ( is_array($items) ) {
$internalCount += array_count($items);
} else {
$internalCount++;
}
}
return $internalCount;
}
}
if ( !function_exists('array_string_contains') ) {
/**
*
* @param array $query
* @param array $array
* @return bool
*/
function array_string_contains( array $query, array $array )
{
$returns = false;
foreach ( $array as $item ) {
foreach ( $query as $value ) {
if ( ( strtolower($item) === strtolower($value) ) ) {
$returns = true;
break;
}
}
if ( $returns ) {
break;
}
}
return $returns;
}
}
if ( !function_exists('array_count_by_column') ) {
/**
* Count items by column and returns the total
*
* @param array $array
* @param string $column
* @param string|null $attribute
* @param bool $count
* @return int
*/
function array_count_by_column( array $array = [], string $column, string $attribute = null, bool $count = true ): int
{
$internalCount = 0;
foreach ( $array as $key => $items ) {
if ( !isset($items[$column]) )
continue;
if ( !is_null($attribute) ) {
$internalCount += array_count_by_column($items[$column], $attribute, null, false);
continue;
}
if ( $count ) {
$internalCount += count($items[$column]);
} else {
$internalCount += $items[$column];
}
}
return $internalCount;
}
}
if ( !function_exists('array_column_with_key') ) {
/**
* Returns and array of the values for each items of the specified column
*
* @param array $array
* @param string $column
* @return array
*/
function array_column_with_key( array $array = [], string $column ): array
{
$internalArray = [];
foreach ( $array as $key => $items ) {
if ( !isset($items[$column]) )
continue;
$internalArray[$key] = $items[$column];
}
return $internalArray;
}
}
if ( !function_exists('array_total_by_column') ) {
/**
* Returns the total of all the values summed values
*
* @param array $array
* @param string $column
* @return int|float
*/
function array_total_by_column( array $array = [], $column )
{
return collect($array)->reduce(function ( $carry, $item ) use ( $column ) {
return $carry + ( $item[$column] ?? 0 );
}, 0);
}
}
if ( !function_exists('str_replace_in_array') ) {
/**
* Replaces the key for the value
*
* @param $string
* @param array $replacements
* @return string
*/
function str_replace_in_array( $string, array $replacements )
{
foreach ( $replacements as $key => $value ) {
$string = str_replace($key, $value, $string);
}
return $string;
}
}
if ( !function_exists('str_replace_config') ) {
/**
* Replaces the key for the value
*
* @param $string
* @return string
*/
function str_replace_config( $string )
{
preg_match_all("/\|([\w\[.\]\\\]+)\|/", $string, $matches);
foreach ( $matches[1] as $key => $value ) {
$k = $matches[0][$key] ?? null;
$string = str_replace($k, config($value, $k), $string);
}
return $string;
}
}
if ( !function_exists('get_real_sentence_from_dictionary') ) {
/**
* Replaces the key for the value
*
* @param $string
* @return string
*/
function get_real_sentence_from_dictionary( $string )
{
$words = explode(" ", $string);
$finalWord = [];
foreach ( $words as $key => $word ) {
$finalWord[] = get_translation(trim($word));
}
return implode(" ", $finalWord);
}
}
if ( !function_exists('get_translation') ) {
/**
* Replaces the key for the value
*
* @param $string
* @return string
*/
function get_translation( $string )
{
return \App\Helpers\TranslationHelper::getInstance()->translate($string);
}
}
if ( !function_exists('str_has_numbers') ) {
/**
* Check if a string has number is it
*
* @param $string
* @return bool
*/
function str_has_numbers( $string ): bool
{
return preg_match('~[0-9]+~', $string);
}
}
if ( !function_exists('change_env_variable') ) {
/**
* Changes variable from .env file
*
* With Great Power Comes Great Responsibility
*
* @param $key
* @param $value
* @return void
*/
function change_env_variable( $key, $value )
{
$path = base_path('.env');
if ( is_bool(env($key)) ) {
$old = env($key) ? 'true' : 'false';
} elseif ( env($key) === null ) {
$old = 'null';
} else {
$old = env($key);
}
if ( file_exists($path) ) {
file_put_contents($path, str_replace(
"$key=" . $old, "$key=" . $value, file_get_contents($path)
));
}
}
}
if ( !function_exists('str_contains_words') ) {
/**
* Check a string match exactly one of the words inside the array
*
* NOTE: Depending on the array length, this method can really impact the performance. Use it wisely
*
* Ahh, hard to see, the Dark Side is.
*
* @param $string
* @param array $words
* @return boolean
*/
function str_contains_words( $string, $words = [] ): bool
{
foreach ( $words as $word ) {
if ( preg_match("/\b({$word})\b/i", $string) ) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment