2017 © Pedro Peláez
 

library laravel-helper

Some helper function for developing applications in laravel

image

repat/laravel-helper

Some helper function for developing applications in laravel

  • Friday, August 5, 2016
  • by repat
  • Repository
  • 1 Watchers
  • 0 Stars
  • 8 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 9 Versions
  • 0 % Grown

The README.md

laravel-helper

Latest Version on Packagist Total Downloads, (*1)

laravel-helper is a package full of helper functions I found useful when developing applications with Laravel. All functions are wrapped with a functions_exists() in case of conflicts., (*2)

Also have a look at * https://laravel.com/docs/5.7/helpers * http://calebporzio.com/11-awesome-laravel-helper-functions/ * https://packagist.org/packages/illuminated/helper-functions, (*3)

Ideas what should go in here? Write a pull request or email!, (*4)

Installation

$ composer require repat/laravel-helper, (*5)

Documentation

Array

array_equal($arr1, $arr2)

Determines if 2 arrays have the same items, independent of order., (*6)

$arr1 = [1, 2, 3];
$arr2 = [3, 2, 1];

array_equal($arr1, $arr2);
// returns: true

$arr3 = [4, 5, 6];
array_equal($arr1, $arr3);
// returns: false

array_key2value($array)

Returns an array where key == value. Syntactic sugar for array_combine($array, $array);, (*7)

$array = [1, 3, 5];

print_r(array_key2value($array));
// returns: Array( [1] => 1, [3] => 3, [5] => 5 )

array_delete_value($array, $value)

Deletes all elements from $array that have value $value. Essentially syntactic sugar for array_diff()., (*8)

$array = ['foo', 'bar'];

print_r(array_delete_value($array, 'foo'));
// returns  Array( [1] => "bar" )

contains_duplicates($array)

Checks if there are duplicates in given array., (*9)

contains_duplicates([1, 1]);
// returns: true
contains_duplicates([1, 2]);
// returns: false

array_change_keys($array, $keys)

Changes the keys recursively for an associative array. The second parameter is an array with the old key (of $array) as the key and the new key as the value., (*10)

$array = [
        'bar' => 'foo',
        'sub' => [
            'some' => 'thing',
        ],
];

$keys = [
    'bar' => 'biz', // change all 'bar' keys to 'biz' keys
    'some' => 'any',
];

array_change_keys($array, $keys);
// returns:[
//         'biz' => 'foo',
//         'sub' => [
//             'any' => 'thing',
//         ],
// ];

array_key_replace($array, $oldKey, $newKey)

Similar to array_change_keys() but it only works for one-dimensional arrays., (*11)

array_key_replace(['bar' => 'foo'], 'bar', 'bizz');
// returns : ['bizz' => 'foo']

Database

mysql_headers($table, $assoc = false)

Returns an array of MySQL headers/columns or empty array in case of an error. If the second parameter is set true (default is false) it returns an associative array., (*12)

print_r(mysql_headers("test_table"));
// returns: Array( [0] => head1, [1] => head2 )

print_r(mysql_headers("test_table", $assoc = true));
// returns: Array( [head1] => head1, [head2] => head2)

table_headers($model)

Returns the database table headers, similar to mysql_headers(), but based on an object of a Eloquent Model., (*13)

use App\Models\User;

$user = User::first();

print_r(table_headers($user));
// returns: Array( 1 => id, 2 => name, ...)

print_r() the session of current user., (*14)

print_db_session();
// returns:
// Array
// (
//     [_token] => 7Au0aYkJVxQVA3xQBfdJwKNaWxUv0UVJKublCqMn
//     [locale] => en
//     ...
// )

get_free_slug($toSlug, $field, $fqcn, $id, $pk)

Returns a unique slug for an Eloquent Model given the following parameters:, (*15)

  • $toSlug: suggestion for the slug
  • $field: name of the database field, usually slug
  • $fqcn: Fully qualified class name of Eloquent Model
  • $id: id to exclude (e.g. it's own on update)
  • $pk: primary key of the database table, defaults to id

Will append a number if $toSlug is already taken., (*16)

use App\Model\User;

$user = User::first();

$user->id;
// returns: 1
$user->slug;
// returns: foobar

get_free_slug('foobar', 'slug', User::class, 1, 'id');
// returns: foobar1

Date

days_in_month($month = null, $year = null)

Returns amount of days in given month or year. Defaults to current month and year., (*17)

days_in_month();
// returns: 31 (for e.g. May)

days_in_month($april = 4);
// returns: 30

days_in_month($feb = 2, $year = 2020);
// returns: 29 (2020 is a leap year)

days_this_month()

Returns amount of days of the current month., (*18)

days_this_month();
// returns: 31 (for e.g. May)

days_next_month()

Returns amount of days of the next month., (*19)

days_next_month();
// returns: 30 (for e.g. May because June has 30)

days_this_year()

Returns amount of days of the current year., (*20)

days_this_year();
// returns: 365 (because it's not a leap year)

days_left_in_month()

Returns amount of days left in current month., (*21)

days_left_in_month();
// returns: 29 (on 1st April)

days_left_in_year()

Returns amount of days left in current year., (*22)

days_left_in_year();
// returns: 274 (on 1st April 2019)

timezone_list()

Returns a list of all timezones., (*23)

timezone_list();
// returns:
// [
// "Pacific/Pago_Pago" => "(UTC-11:00) Pacific/Pago_Pago",
// "Pacific/Niue" => "(UTC-11:00) Pacific/Niue",
// "Pacific/Midway" => "(UTC-11:00) Pacific/Midway",
// ...
// "Pacific/Chatham" => "(UTC+13:45) Pacific/Chatham",
// "Pacific/Kiritimati" => "(UTC+14:00) Pacific/Kiritimati",
// "Pacific/Apia" => "(UTC+14:00) Pacific/Apia",
// ];

tomorrow()

Similar to today() or now(), this function returns a Carbon instance for tomorrow., (*24)

tomorrow();
// returns: Carbon\Carbon @1554156000 {#5618
//     date: 2019-04-20 00:00:00.0 Europe/Amsterdam (+02:00),
//   }

seconds2minutes($seconds)

Returns i:s string with 60+ minutes instead of showing the hours as well., (*25)

seconds2minutes(42);
// returns: 00:42

seconds2minutes(90);
// returns: 01:30

seconds2minutes(4223);
// returns: 70:23

Object

morph_map()

Returns the morphMap from AppServiceProvider set with Relation::morphMap()., (*26)

morph_map();
// returns:Array
// (
//     [user] => App\Models\User
// )

morph_map_key($fqcn)

Reverse lookup for a class in the morphMap of the AppServiceProvider set with Relation::morphMap()., (*27)

use App\Models\User;

morph_map_key(User::class);
// returns: 'user'

object2array($object)

Array representation of an object, e.g. an Eloquent Model., (*28)

use App\Models\User;

object2array(User::first());
// returns: [
//      "casts" => [
//        "someday_at" => "datetime",
//       // ...
//      ],
//      "incrementing" => true,
//      "exists" => true,
//      "wasRecentlyCreated" => false,
//      "timestamps" => true,
// ]

cache_get_or_add($key, $callable)

Returns Cache for given key or adds the return value from the callable to the cache and then returns it., (*29)

use App\Models\Post;

$posts = cache_get_or_add('posts', function() {
    return Post::orderBy('created_at', 'desc')->get();
});

filepath2fqcn($filepath, $prefix = '')

Will turn a filepath into a Fully Qualified Class Name., (*30)

filepath2fqcn('/Users/john/code/app/Models/User.php', '/Users/john/code/');
// returns: App\Models\User

filepath2fqcn('/Users/john/code/app/Models/User.php', '/Users/john/code');
// returns: App\Models\User

filepath2fqcn('app/Models/User.php');
// returns: App\Models\User

filepath2fqcn('/Users/john/code/app/Models/User.php');
// returns: \Users\john\code\app\Models\User

Misc

toggle($switch)

If given true, returns false and vice-versa., (*31)

toggle(false);
// returns: true

toggle(true);
// returns: false

generate_password($size = 15)

Returns a random password. Syntactic sugar for str_random()., (*32)

generate_password();
// returns: IZeJx3MeUdDhzE2

auto_cast($value)

Returns the value with the right type so e.g. you can compare type safe with ===., (*33)

gettype(auto_cast('42'));
// returns: integer
gettype(auto_cast('42.0'));
// returns: double
gettype(auto_cast('true'));
// returns: boolean

human_filesize($size)

Returns a human readable form for given bytes. Goes up to Yottabyte., (*34)

human_filesize(4223);
// returns: 4.12kB

permutations($array)

Returns a generator with all possible permutations of given array values., (*35)

Based on eddiewoulds port port of python code., (*36)

$gen = permutations(['foo', 'bar', 'biz']);

iterator_to_array($gen)
// returns: [
   //   [
   //     "foo",
   //     "bar",
   //     "biz",
   //   ],
   //   [
   //     "foo",
   //     "biz",
   //     "bar",
   //   ],
   //   [
   //     "bar",
   //     "foo",
   //     "biz",
   //   ],
   //   [
   //     "bar",
   //     "biz",
   //     "foo",
   //   ],
   //   [
   //     "biz",
   //     "foo",
   //     "bar",
   //   ],
   //   [
   //     "biz",
   //     "bar",
   //     "foo",
   //   ],
   // ]

zenith($type)

Wrapper around magic numbers for the Zenith. The types can be:, (*37)

  • astronomical: 108.0
  • nautical: 102.0
  • civil: 96.0
  • default: 90+50/60 (~90.83)
zenith('civil');
// returns: 96.0

operating_system()

Returns on of the following constants (also see under constants):, (*38)

  • macos
  • windows
  • linux
  • bsd
operating_system();
// returns: linux
LINUX
// returns: linux

wikipedia($lemma, $lang = 'en', $return = '')

Link URL to wikipedia for a certain language, (*39)

wikipedia('Towel Day');
// returns: https://en.wikipedia.org/wiki/Towel_Day

wikipedia('Paris', 'fr', '#')
// returns: https://fr.wikipedia.org/wiki/Paris

wikipedia('Pariz', 'fr', '#')
// returns: #

Networking

route_path($path)

Get the path to the Laravel routes folder, similar to app_path(), see Helpers Documentation. It will append $path but it's not mandatory., (*40)

route_path();
// returns: /var/www/htdocs/laravel/routes

route_path('web.php');
// returns: /var/www/htdocs/laravel/routes/web.php

named_routes($path, $verb)

Returns array of all named routes in a routes file or null on error. It's possible to pass an HTTP verb/method defined in HTTP_VERBS_LARAVEL (see below)., (*41)

named_routes('/var/www/htdocs/laravel/routes/web.php');
// returns: [
// 'laravel.get'
// 'laravel.post'
// ]

named_routes('/var/www/htdocs/laravel/routes/web.php', 'get');
// returns: [
// 'laravel.get'
// ]

scrub_url($url)

Removes the protocol, www and trailing slashes from a URL. You can then e.g. test HTTP vs. HTTPS connections., (*42)

scrub_url('https://www.repat.de/');
// returns: 'repat.de'

scrub_url('https://blog.fefe.de/?ts=a262bcdf');
// returns: 'blog.fefe.de/?ts=a262bcdf'

http_status_code($url)

Returns just the status code by sending an empty request with curl. Follows redirect so it will only return the last status code and not e.g. 301 Redirects. Requires ext-curl., (*43)

http_status_code('httpstat.us/500');
// returns: 500

http_status_code('http://repat.de'); // with 301 redirect to https://repat.de
// returns: 200

parse_signed_request($request, $clientSecret, $algo)

Parses a HMAC signed request. Copied from Data Deletion Request Callback - Facebook for Developers. $algo defaults to sha256., (*44)

$requestString = null; // TODO
parse_signed_request($requestString, env('FACEBOOK_CLIENT_SECRET'));

domain_slug($domain)

Validates a domain and creates a slug. Does not work for subdomains, see sluggify_domain() instead. Returns null on a parsing error., (*45)

domain_slug('blog.fefe.de')
//returns: blogfefede
domain_slug('blogfefe.de')
//returns: blogfefede
current_route_name()

If the current route has a name, otherwise return null., (*46)

// in routes/web.php
// Route::name('dev.foo')->get('foo', 'Dev\TestController@foo');
// Route::get('bar', 'Dev\TestController@bar');

// in Dev/TestController@foo
current_route_name();
// returns: dev.foo

// in Dev/TestController@foo
current_route_name();
// returns: null

String

str_icontains($haystack, $needle)

Similar to Str::contains() but case insensitive., (*47)

str_icontains('FOOBAR', 'foo');
// returns: true

str_icontains('foobar', 'foo');
// returns: true

str_icontains('foobar', 'FOO');
// returns: true

str_icontains('foobar', 'test');
// returns: false

to_ascii($string)

Removes all non ASCII characters and returns the rest., (*48)

to_ascii('René');
// returns: Ren

hyphen2_($string)

Replaces all hyphen ("-") characters with underscore ("_"), (*49)

hyphen2_('foo-bar');
// returns: foo_bar

_2hypen($string)

Replaces all underscore ("_") characters with hyphen ("-"), (*50)

hyphen2_('foo_bar');
// returns: foo-bar

str_replace_once($search, $replace, $string)

Same signature as str_replace(), but as name suggests, replaces only the first occurrence of $search., (*51)

str_replace_once('foo', 'bar', 'foofoo');
// returns: 'barfoo'

title_case_wo_underscore($string)

Title Case but without underscores., (*52)

title_case_wo_underscore('foo_bar');
// returns: Foo Bar

// vs.
// title_case('foo_bar')
// returns: Foo_Bar

lorem_ipsum()

Returns an example of the Lorem Ipsum placeholder text., (*53)

lorem_ipsum();
// returns:
// Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

sluggify_domain($domain)

Returns a slug version of the domain by exchanging full stops with underscores. str_slug() does not work with subdomains, as it removes full stops completely., (*54)

sluggify_domain('blog.fefe.de');
// returns: blog_fefe_de
str_slug('blog.fefe.de');
// returns: blogfefede

sluggify_domain('blogfefe.de');
// returns: blogfefe_de
str_slug('blogfefe.de');
// returns: blogfefede // same as subdomain on fefe.de

str_remove($string, $remove)

Removes given string(s), numbers or array of strings. Syntactic sugar for str_replace($remove, '', $string)., (*55)

str_remove('foobar', 'bar');
// returns: foo
str_remove('foobar42', ['foo', 'bar']);
// returns: 42
str_remove('foobar42', 42);
// returns: foobar

str_bytes($string)

Returns the amount of bytes in a string., (*56)

str_bytes('foobar');
// returns: 6
str_bytes('fooßar');
// returns: 8

regex_list($array)

Creates a string with regex for an OR separated list., (*57)

regex_list(['foo', 'bar', '42'])
// returns: \bfoo|\bbar|\b42

base64_url_decode($url)

Decodes a base64-encoded URL. Copied from Data Deletion Request Callback - Facebook for Developers, (*58)

base64_url_decode('aHR0cHM6Ly9yZXBhdC5kZQ==');
// returns: https://repat.de

str_right($string, $until)

Substring from the right until given string, see also str_left(). Will return the input string if $until is not present., (*59)

str_right('https://vimeo.com/165053513', '/');
// returns: 165053513

str_left($string, $before)

Syntactic sugar for str_before to be consistent with str_right()., (*60)

Optional Packages

Optional packages suggested by this are required for these functions to work., (*61)

markdown2html($markdown)

Uses league/commonmark to transform Markdown into HTML., (*62)

  • $ composer require league/commonmark
markdown2html('# Header');
// returns: <h1>Header</h1>\n

translated_attributes($fqcn)

Uses dimsav/laravel-translatable and Reflection to get the translatedAttributes attribute of a Model., (*63)

  • $ composer require dimsav/laravel-translatable
use App\Models\Product;

translated_attributes(Product::class);
// returns: ['title', 'description'];

domain($url)

Uses layershifter/tld-extract to return the domain only from a URL, removing protocol, subdomain and path., (*64)

  • $ composer require layershifter/tld-extract
domain('https://repat.de/about?foo=bar');
// returns: repat.de

HTML

linkify($string, $protocols = ['http', 'https', 'mail'], $attributes)

Returns the string with all URLs for given protocols made into links. Optionally, attributes for the a tag can be passed., (*65)

linkify('https://google.com is a search engine');
// returns: <a  href="https://google.com">google.com</a> is a search engine

linkify('https://google.com is a search engine', ['https'], ['target' => '_blank']);
// returns: <a target="_blank" href="https://google.com">google.com</a> is a search engine

embedded_video_url($url)

Returns the embedded version of a given YouTube or Vimeo URL., (*66)

embedded_video_url('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
// returns: https://www.youtube.com/embed/dQw4w9WgXcQ

embedded_video_url('https://vimeo.com/50491748');
// returns: https://player.vimeo.com/video/50491748

ul_li_unpack($array, $separator)

Unpacks an associated array into an unordered list. Default separator is :., (*67)

ul_li_unpack(['foo' => 'bar']);
// returns: 

  • foo: bar
ul_li_unpack(['foo' => 'bar'], '=>'); // returns:
  • foo=> bar

extract_inline_img($text, $storagePath, $srcPath, $optimize)

Extracts an inline image from a text, saves it on the harddrive and puts in the filename with the src attribute. Can use the spatie/laravel-image-optimizer to optimize images after upload but it's disabled by default., (*68)

  • $ composer require spatie/laravel-image-optimizer
extract_inline_img("<img src='data:image/jpeg;base64,...>", '/var/www/htdocs/laravel/storage/foobar', 'public/images', true);
// returns: <img src="public/images/fj3209fjew93.jpg">

Constants

  • PARETO_HIGH: 80
  • PARETO_LOW: 20
  • MARIADB_DEFAULT_STRLEN: 191
  • MULTIPLE_TRANS: 2
  • ONE_HUNDRED_PERCENT: 100
  • HTTP_1_0_VERBS: [get, head, post]
  • HTTP_1_1_VERBS: [get, head, post, connect, delete, options, put, trace]
  • HTTP_VERBS: [get, head, post, connect, delete, options, put, trace, patch]
  • HTTP_VERBS_LARAVEL: [all, get, head, post, delete, options, put, patch]
  • REGEX_WORD_BOUNDARY: \b
  • REGEX_IMG_BASE64_SRC: Regular Expression used to find a base64 encoded image in HTML text
  • REGEX_IMG_BASE64_REPLACE: Regular Expression used to replace a base64 encoded image in HTML text
  • REGEX_FIRST_RESULT_KEY: 1
  • MACOS: macos
  • WINDOWS: windows
  • LINUX: linux
  • BSD: bsd
  • WEAK_CIPHERS : [ TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA]

Contributors

  • https://github.com/bertholf

License

Version

  • Version 0.1.31

Contact

repat

  • Homepage: https://repat.de
  • e-mail: repat@repat.de
  • Twitter: @repat123

Flattr this git repo, (*69)

The Versions

05/08 2016

dev-master

9999999-dev http://repat.de

Some helper function for developing applications in laravel

  Sources   Download

MIT

The Requires

 

by Avatar repat

database laravel strings helper files header

05/08 2016

0.1.7

0.1.7.0 http://repat.de

Some helper function for developing applications in laravel

  Sources   Download

MIT

The Requires

 

by Avatar repat

database laravel strings helper files header

22/02 2016

0.1.6

0.1.6.0 http://repat.de

Some helper function for developing applications in laravel

  Sources   Download

MIT

The Requires

 

by Avatar repat

database laravel strings helper files header

13/12 2015

0.1.5

0.1.5.0 http://repat.de

Some helper function for developing applications in laravel

  Sources   Download

MIT

The Requires

 

by Avatar repat

database laravel strings helper files header

10/12 2015

0.1.4

0.1.4.0 http://repat.de

Some helper function for developing applications in laravel

  Sources   Download

MIT

The Requires

 

by Avatar repat

database laravel strings helper files header

09/12 2015

0.1.3

0.1.3.0 http://repat.de

Some helper function for developing applications in laravel

  Sources   Download

MIT

The Requires

 

by Avatar repat

database laravel strings helper files header

09/12 2015

0.1.2

0.1.2.0 http://repat.de

Some helper function for developing applications in laravel

  Sources   Download

MIT

The Requires

 

by Avatar repat

database laravel strings helper files header

09/12 2015

0.1.1

0.1.1.0 http://repat.de

Some helper function for developing applications in laravel

  Sources   Download

MIT

The Requires

 

by Avatar repat

database laravel strings helper files header

09/12 2015

0.1

0.1.0.0 http://repat.de

Some helper function for developing applications in laravel

  Sources   Download

MIT

The Requires

 

by Avatar repat

database laravel strings helper files header