Skip to content

Instantly share code, notes, and snippets.

@nissicreative
Last active September 12, 2017 14:15
Show Gist options
  • Save nissicreative/5fdd3600eaf8f981d1236e0147772879 to your computer and use it in GitHub Desktop.
Save nissicreative/5fdd3600eaf8f981d1236e0147772879 to your computer and use it in GitHub Desktop.
Laravel Helper Functions
<?php
use Carbon\Carbon;
use Nissi\Proxies\Date;
use Nissi\Proxies\Text;
use Nissi\Proxies\Format;
use Nissi\Proxies\Number;
use Nissi\Proxies\Inflect;
use Nissi\Proxies\Geography;
use Nissi\ValueObjects\Gravatar;
use Nissi\ValueObjects\PostalAddress;
/*
|--------------------------------------------------------------------------
| App-specific Data
|--------------------------------------------------------------------------
*/
/**
* Name of the app/organization.
*/
function site_name()
{
return Config::get('app.name');
}
/**
* mailto: link to primary contact email address.
*/
function contact_email($anchortext = null)
{
return Html::mailto(Config::get('contact.email'), $anchortext);
}
/**
* Email address for outbound messages.
*/
function from_address()
{
return Config::get('mail.from.address');
}
/**
* Email "from" name for outbound messages.
*/
function from_name()
{
return Config::get('mail.from.name');
}
/**
* Email address for inbound messages.
*/
function recipient_address()
{
return Config::get('contact.recipient.address');
}
/**
* Email "to" name for inbound messages.
*/
function recipient_name()
{
return Config::get('contact.recipient.name');
}
/**
* Returns an object suitable for using in `Mail::to()` method.
*/
function default_recipient()
{
return (object) [
'email' => Config::get('contact.recipient.address'),
'name' => Config::get('contact.recipient.name'),
];
}
/**
* Formatted contact phone number.
*/
function contact_phone($format = null)
{
$format = $format ?: Config::get('prefs.phone_format');
return format_phone(Config::get('contact.phone'), $format);
}
/**
* Formatted contact fax number.
*/
function contact_fax($format = null)
{
$format = $format ?: Config::get('prefs.phone_format');
return format_phone(Config::get('contact.fax'), $format);
}
/**
* PostalAddress object. Can be formatted fluently.
*/
function contact_address()
{
return new PostalAddress(Config::get('contact'));
}
/**
* Builds content for a page's <title> tag.
*/
function page_title($title = '', $separator = null, $position = 'left')
{
$separator = $separator ?: Config::get('prefs.title_separator', ' | ');
if ( ! $title) {
$separator = '';
}
if ($position == 'right') {
return site_name() . $separator . $title;
}
return $title . $separator . site_name();
}
/*
|--------------------------------------------------------------------------
| URL Helpers
|--------------------------------------------------------------------------
*/
/**
* Generate a mailto: link to the given address.
*/
function mailto($email, $title = null, $attributes = [])
{
if (empty($email)) {
return;
}
return Html::mailto($email, $title, $attributes);
}
/**
* Link to a website. By default, use a schemeless version
* of the URL as the anchor text.
*/
function website_link($url, $title = null, $options = [])
{
$defaults = ['use_scheme' => false];
$options += $defaults;
$title = $title ?? Format::url($url, $options);
return link_to($url, $title);
}
/**
* Return the Gravatar URI for an email address.
*/
function gravatar_src($email = null, $size = null, $default = null)
{
return (new Gravatar())->getSrc($email, $size, $default);
}
/**
* Obfuscate an email address.
*/
function email($email)
{
return Html::email($email);
}
/**
* Determine if current route is the route name provided.
*/
function route_is($string = '')
{
if (empty(request()->route()) || ! $routeName = request()->route()->getName()) {
return false;
}
return $routeName == $string;
}
/**
* Determine if a named route starts with a given string.
*/
function route_starts_with($string = '')
{
if (empty(request()->route()) || ! $routeName = request()->route()->getName()) {
return false;
}
return starts_with($routeName, $string);
}
/**
* Determine if a named route ends with a given string.
*/
function route_ends_with($string = '')
{
if (empty(request()->route()) || ! $routeName = request()->route()->getName()) {
return false;
}
return ends_with($routeName, $string);
}
/**
* Determine if a named route contains a given string.
*/
function route_contains($string = '')
{
if (empty(request()->route()) || ! $routeName = request()->route()->getName()) {
return false;
}
return str_contains($routeName, $string);
}
/*
|--------------------------------------------------------------------------
| Data Generator Helpers
|--------------------------------------------------------------------------
*/
/**
* Returns a Carbon instance (or formatted string) on success,
* Returns null on failure (i.e. invalid date)
*/
function make_date($datestring, $format = null, $onEmpty = null)
{
try {
// No date string provided. Return null.
if (empty($datestring)) {
return $onEmpty;
}
// Invalid date. Return null.
if ( ! $dt = Carbon::parse($datestring)) {
return $onEmpty;
}
// Date out of range. Return null.
if ($dt < Carbon::minValue() || $dt > Carbon::maxValue()) {
return $onEmpty;
}
// Return a formatted string.
if ($format) {
return $dt->format($format);
}
// Return Carbon instance
return $dt;
} catch (Exception $e) {
return $onEmpty;
}
}
/**
* Shorthand for creating a new Carbon instance.
*/
if ( ! function_exists('now')) {
function now()
{
return Carbon::now();
}
}
/**
* Return a PostalAddress object from an array of address data.
*/
function make_address(array $data)
{
return new PostalAddress($data);
}
/**
* Make a well-formatted person name from a data array (i.e. request data).
*/
function make_name(array $data)
{
return (new PostalAddress($data))->getName();
}
/**
* Make a unique slug for a table.
*/
function make_slug($string, $table = 'posts', $column = 'slug')
{
$slug = str_slug($string);
$count = DB::table($table)->whereRaw("{$column} RLIKE '^{$slug}(-[0-9]+)?$'")->count();
return $count ? sprintf('%s-%s', $slug, $count + 1) : $slug;
}
/**
* Make check marks (i.e. for displaying boolean values in views).
*/
function make_check($val, $yes = null, $no = null)
{
$yes = $yes !== null ? $yes : config('prefs.icons.yes', '<i class="fa fa-check-square text-success"></i>');
$no = $no !== null ? $no : config('prefs.icons.no', '<i class="fa fa-ban text-danger"></i>');
return $val ? $yes : $no;
}
/**
* Mark an element (i.e. table row) inactive based on $val.
*/
function mark_inactive($val, $classname = ' inactive')
{
if (empty($val)) {
echo $classname;
}
}
/**
* Generate a v4 UUID.
* @see http://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid
*/
function make_uuid()
{
$data = openssl_random_pseudo_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
/**
* Mask a credit card number.
*/
function mask_cc($number, $char = 'X')
{
if (strlen($number) < 5) {
return str_repeat($char, strlen($number) - 1) . substr($number, -1);
}
return substr($number, 0, 2) . str_repeat($char, strlen($number) - 6) . substr($number, -4);
}
/*
|--------------------------------------------------------------------------
| File Helpers
|--------------------------------------------------------------------------
*/
/**
* Create a directory with appropriate file permissions.
*/
function make_directory($path, $mode = 0755, $recursive = true, $force = true)
{
return File::exists($path) or File::makeDirectory($path, $mode, $recursive, $force);
}
/*
|--------------------------------------------------------------------------
| Data Formatters
|--------------------------------------------------------------------------
*/
/**
* Format a phone number according to preferences.
*/
function format_phone($phone, $format = null, array $options = [])
{
$format = $format ?: Config::get('prefs.phone_format');
return Format::phone($phone, $format, $options);
}
/**
* Format a URL.
*/
function format_url($url, array $options = [])
{
return Format::url($url, $options);
}
/**
* Left-pad a number.
*/
function number_pad($number, $length = 5, $pad_string = '0')
{
return str_pad($number, $length, $pad_string, STR_PAD_LEFT);
}
/**
* Format a social security number.
*/
function format_ssn($string, $separator = '-')
{
return Format::ssn($string, $separator);
}
/**
* Friendly representation of file size.
*/
function format_bytes($bytes, $precision = 2)
{
return Format::bytes($bytes, $precision);
}
/*
|--------------------------------------------------------------------------
| Number Formatters
|--------------------------------------------------------------------------
*/
/**
* Format a number as currency: 1234.00
*/
function currency($amount, $options = [])
{
return Number::currency($amount, $options);
}
/**
* Format a number as a percentage.
*/
function percentage($amount, $precision = 0, $options = [])
{
return Number::percentage($amount, $precision, $options);
}
/**
* Format a number as an ordinal.
*/
function ordinal($number)
{
return Number::ordinal($number);
}
/*
|--------------------------------------------------------------------------
| String Helpers
|--------------------------------------------------------------------------
*/
/**
* Return HTML from a Markdown string using Parsedown library.
*/
function parsedown($text)
{
return (new Parsedown())->text($text);
}
/**
* Truncate a string to a given length.
*/
function truncate($string, $length = 20, $options = [])
{
return Text::truncate($string, $length, $options);
}
/**
* Truncate a string to a given length, preserving beginning and end.
*/
function mtruncate($string, $length = 20, $separator)
{
return Text::mtruncate($string, $length, $separator);
}
/**
* Smarter alternative to Laravel's title_case function.
*/
function strtotitle($string)
{
return Text::titleCase(strtolower($string));
}
/**
* Smart pluralization.
*/
function pluralize($string)
{
return Inflect::pluralize($string);
}
/**
* Smart singularization.
*/
function singularize($string)
{
return Inflect::singularize($string);
}
/**
* Smart pluralization based on number of items.
*/
function pluralize_if($string, $count = 0, $include_count = true)
{
return Inflect::pluralizeIf($string, $count, $include_count);
}
/**
* Format a database column name as a title.
*/
function str_humanize($string)
{
$string = trim($string);
$string = preg_replace('/_id$/', '', $string);
return strtotitle(preg_replace('/[_-]+/', ' ', $string));
}
/**
* Return a boolean indicating whether input is valid JSON.
*/
function is_json($input)
{
return is_string($input) && json_decode($input);
}
/**
* Split a full name into pieces.
*/
function split_name($name)
{
$name = trim($name);
$last_name = (strpos($name, ' ') === false)
? ''
: preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim(preg_replace('#' . $last_name . '#', '', $name));
return [$first_name, $last_name];
}
/*
|--------------------------------------------------------------------------
| Array Helpers
|--------------------------------------------------------------------------
*/
/**
* Makes array keys the same as the values. Useful for select elements.
*/
function array_reflect($arr = [])
{
return array_combine(array_values($arr), array_values($arr));
}
/**
* Return a human readable key/value map of an associative array.
*/
function array_format($array, $separator = "\n<br>")
{
return collect($array)
->map(function ($val, $key) {
return sprintf('%s: %s', str_humanize($key), $val);
})
->implode($separator);
}
/*
|--------------------------------------------------------------------------
| Menu Helpers
|--------------------------------------------------------------------------
*/
/**
* Determine if a given menu item is "active" based on URL.
*
* @return string
*/
function set_active($pathName, $className = 'active', $excluded = null)
{
if ($excluded && call_user_func_array('Request::is', (array) $excluded)) {
return '';
}
return call_user_func_array('Request::is', (array) $pathName) ? $className : '';
}
/**
* Determine if a given menu item is active based on named route.
*
* @return string
*/
function set_active_route($routeName, $className = 'active')
{
if ( ! Request::route()) {
return;
}
return (Request::route()->getName() == $routeName) ? $className : '';
}
/*
|--------------------------------------------------------------------------
| Form Helpers
|--------------------------------------------------------------------------
*/
/**
* Array of US states in $abbrev => $name format.
*/
function us_states()
{
return Geography::usStates();
}
/**
* Array with months of the year with formatted keys and values.
*/
function months_of_year($keyFormat = 'm', $valFormat = 'F (m)')
{
return Date::monthsOfYear($keyFormat, $valFormat);
}
/**
* Array with days of a given month. Default to January (31 days).
*/
function days_of_month($month = '1', $year = null)
{
return Date::daysOfMonth($month, $year);
}
/**
* Array of years with formatted keys and values.
*/
function years($start = null, $end = null, $keyFormat = 'Y', $valFormat = 'Y')
{
return Date::years($start, $end, $keyFormat, $valFormat);
}
/**
* Array of years starting n years in the past.
*/
function years_past($start = 100, $end = 0, $keyFormat = 'Y', $valFormat = 'Y')
{
$start = Carbon::now()->subYears($start)->format('Y');
$end = Carbon::now()->subYears($end)->format('Y');
return Date::years($start, $end, $keyFormat, $valFormat);
}
/**
* Yes/No
*/
function yn()
{
return array_reflect(['Yes', 'No']);
}
/**
* Yes/No/Somewhat
*/
function yns()
{
return array_reflect(['Yes', 'No', 'Somewhat']);
}
/**
* Yes/No/Maybe
*/
function ynm()
{
return array_reflect(['Yes', 'No', 'Maybe']);
}
/**
* Yes/No/Don't Know
*/
function ynd()
{
return array_reflect(['Yes', 'No', 'Don’t Know']);
}
/*
|--------------------------------------------------------------------------
| Debugging Helpers
|--------------------------------------------------------------------------
*/
/**
* `print_r` inside a `pre` tag.
*/
function pr($var, $exit = false)
{
echo '<pre>';
print_r($var);
echo '</pre>' . PHP_EOL;
if ($exit) {
exit;
}
}
/**
* `var_dump` inside a `pre` tag.
*/
function vd($var, $exit = true)
{
echo '<pre>';
var_dump($var);
echo "</pre>\n";
if ($exit) {
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment